blob: f9f5458122ffefdd87df23b26bc37c69e719ff33 [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;
Christopher Tate336a6492011-10-05 16:05:43 -0700231 volatile boolean mBackupRunning;
Christopher Tate73e02522009-07-15 14:18:26 -0700232 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700233 volatile long mLastBackupPass;
234 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700235
Christopher Tate55f931a2009-09-29 17:17:34 -0700236 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700237 final Object mClearDataLock = new Object();
238 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700239
Christopher Tate91717492009-06-26 21:07:13 -0700240 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700241 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700242 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700243 String mCurrentTransport;
244 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800245 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700246
Christopher Tate2d449afe2010-03-29 19:14:24 -0700247 class RestoreGetSetsParams {
248 public IBackupTransport transport;
249 public ActiveRestoreSession session;
250 public IRestoreObserver observer;
251
252 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
253 IRestoreObserver _observer) {
254 transport = _transport;
255 session = _session;
256 observer = _observer;
257 }
258 }
259
Christopher Tate73e02522009-07-15 14:18:26 -0700260 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700261 public IBackupTransport transport;
262 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700263 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800264 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800265 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700266 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700267 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800268
269 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700270 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800271 transport = _transport;
272 observer = _obs;
273 token = _token;
274 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800275 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700276 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700277 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800278 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700279
Chris Tate249345b2010-10-29 12:57:04 -0700280 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
281 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700282 transport = _transport;
283 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700284 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800285 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800286 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700287 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700288 filterSet = null;
289 }
290
291 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
292 String[] _filterSet, boolean _needFullBackup) {
293 transport = _transport;
294 observer = _obs;
295 token = _token;
296 pkgInfo = null;
297 pmToken = 0;
298 needFullBackup = _needFullBackup;
299 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700300 }
301 }
302
Christopher Tate73e02522009-07-15 14:18:26 -0700303 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700304 public IBackupTransport transport;
305 public PackageInfo packageInfo;
306
307 ClearParams(IBackupTransport _transport, PackageInfo _info) {
308 transport = _transport;
309 packageInfo = _info;
310 }
311 }
312
Christopher Tate4a627c72011-04-01 14:43:32 -0700313 class FullParams {
314 public ParcelFileDescriptor fd;
315 public final AtomicBoolean latch;
316 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700317 public String curPassword; // filled in by the confirmation step
318 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700319
320 FullParams() {
321 latch = new AtomicBoolean(false);
322 }
323 }
324
325 class FullBackupParams extends FullParams {
326 public boolean includeApks;
327 public boolean includeShared;
328 public boolean allApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700329 public boolean includeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700330 public String[] packages;
331
332 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
Christopher Tate240c7d22011-10-03 18:13:44 -0700333 boolean doAllApps, boolean doSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -0700334 fd = output;
335 includeApks = saveApks;
336 includeShared = saveShared;
337 allApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -0700338 includeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -0700339 packages = pkgList;
340 }
341 }
342
343 class FullRestoreParams extends FullParams {
344 FullRestoreParams(ParcelFileDescriptor input) {
345 fd = input;
346 }
347 }
348
Christopher Tate44a27902010-01-27 17:15:49 -0800349 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
350 // token is the index of the entry in the pending-operations list.
351 static final int OP_PENDING = 0;
352 static final int OP_ACKNOWLEDGED = 1;
353 static final int OP_TIMEOUT = -1;
354
Christopher Tate8e294d42011-08-31 20:37:12 -0700355 class Operation {
356 public int state;
357 public BackupRestoreTask callback;
358
359 Operation(int initialState, BackupRestoreTask callbackObj) {
360 state = initialState;
361 callback = callbackObj;
362 }
363 }
364 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800365 final Object mCurrentOpLock = new Object();
366 final Random mTokenGenerator = new Random();
367
Christopher Tate4a627c72011-04-01 14:43:32 -0700368 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
369
Christopher Tate5cb400b2009-06-25 16:03:14 -0700370 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700371 File mBaseStateDir;
372 File mDataDir;
373 File mJournalDir;
374 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700375
Christopher Tate2efd2db2011-07-19 16:32:49 -0700376 // Backup password, if any, and the file where it's saved. What is stored is not the
377 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
378 // persisted) salt. Validation is performed by running the challenge text through the
379 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
380 // the saved hash string, then the challenge text matches the originally supplied
381 // password text.
382 private final SecureRandom mRng = new SecureRandom();
383 private String mPasswordHash;
384 private File mPasswordHashFile;
385 private byte[] mPasswordSalt;
386
387 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
388 static final int PBKDF2_HASH_ROUNDS = 10000;
389 static final int PBKDF2_KEY_SIZE = 256; // bits
390 static final int PBKDF2_SALT_SIZE = 512; // bits
391 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
392
Christopher Tate84725812010-02-04 15:52:40 -0800393 // Keep a log of all the apps we've ever backed up, and what the
394 // dataset tokens are for both the current backup dataset and
395 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700396 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700397 HashSet<String> mEverStoredApps = new HashSet<String>();
398
Christopher Tateb49ceb32010-02-08 16:22:24 -0800399 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800400 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800401 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800402 long mAncestralToken = 0;
403 long mCurrentToken = 0;
404
Christopher Tate4cc86e12009-09-21 19:36:51 -0700405 // Persistently track the need to do a full init
406 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
407 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700408
Christopher Tate4a627c72011-04-01 14:43:32 -0700409 // Utility: build a new random integer token
410 int generateToken() {
411 int token;
412 do {
413 synchronized (mTokenGenerator) {
414 token = mTokenGenerator.nextInt();
415 }
416 } while (token < 0);
417 return token;
418 }
419
Christopher Tate44a27902010-01-27 17:15:49 -0800420 // ----- Asynchronous backup/restore handler thread -----
421
422 private class BackupHandler extends Handler {
423 public BackupHandler(Looper looper) {
424 super(looper);
425 }
426
427 public void handleMessage(Message msg) {
428
429 switch (msg.what) {
430 case MSG_RUN_BACKUP:
431 {
432 mLastBackupPass = System.currentTimeMillis();
433 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
434
435 IBackupTransport transport = getTransport(mCurrentTransport);
436 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800437 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate336a6492011-10-05 16:05:43 -0700438 synchronized (mQueueLock) {
439 mBackupRunning = false;
440 }
Christopher Tate44a27902010-01-27 17:15:49 -0800441 mWakelock.release();
442 break;
443 }
444
445 // snapshot the pending-backup set and work on that
446 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800447 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800448 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800449 // Do we have any work to do? Construct the work queue
450 // then release the synchronization lock to actually run
451 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800452 if (mPendingBackups.size() > 0) {
453 for (BackupRequest b: mPendingBackups.values()) {
454 queue.add(b);
455 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800456 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800457 mPendingBackups.clear();
458
459 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800460 mJournal = null;
461
Christopher Tate44a27902010-01-27 17:15:49 -0800462 }
463 }
Christopher Tatec61da312010-02-05 10:41:27 -0800464
Christopher Tate8e294d42011-08-31 20:37:12 -0700465 // At this point, we have started a new journal file, and the old
466 // file identity is being passed to the backup processing task.
467 // When it completes successfully, that old journal file will be
468 // deleted. If we crash prior to that, the old journal is parsed
469 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800470 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700471 // Spin up a backup state sequence and set it running
472 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
473 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
474 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800475 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800476 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tate336a6492011-10-05 16:05:43 -0700477 synchronized (mQueueLock) {
478 mBackupRunning = false;
479 }
Christopher Tatec61da312010-02-05 10:41:27 -0800480 mWakelock.release();
481 }
Christopher Tate44a27902010-01-27 17:15:49 -0800482 break;
483 }
484
Christopher Tate8e294d42011-08-31 20:37:12 -0700485 case MSG_BACKUP_RESTORE_STEP:
486 {
487 try {
488 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
489 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
490 task.execute();
491 } catch (ClassCastException e) {
492 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
493 }
494 break;
495 }
496
497 case MSG_OP_COMPLETE:
498 {
499 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700500 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
501 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700502 } catch (ClassCastException e) {
503 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
504 }
505 break;
506 }
507
Christopher Tate44a27902010-01-27 17:15:49 -0800508 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700509 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700510 // TODO: refactor full backup to be a looper-based state machine
511 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700512 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700513 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
514 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700515 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -0700516 params.allApps, params.includeSystem, params.packages, params.latch);
Christopher Tatea28e8542011-09-12 13:45:21 -0700517 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800518 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700519 }
Christopher Tate44a27902010-01-27 17:15:49 -0800520
521 case MSG_RUN_RESTORE:
522 {
523 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800524 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700525 PerformRestoreTask task = new PerformRestoreTask(
526 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700527 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700528 params.needFullBackup, params.filterSet);
529 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
530 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800531 break;
532 }
533
Christopher Tate75a99702011-05-18 16:28:19 -0700534 case MSG_RUN_FULL_RESTORE:
535 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700536 // TODO: refactor full restore to be a looper-based state machine
537 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700538 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700539 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
540 params.curPassword, params.encryptPassword,
541 params.observer, params.latch);
542 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700543 break;
544 }
545
Christopher Tate44a27902010-01-27 17:15:49 -0800546 case MSG_RUN_CLEAR:
547 {
548 ClearParams params = (ClearParams)msg.obj;
549 (new PerformClearTask(params.transport, params.packageInfo)).run();
550 break;
551 }
552
553 case MSG_RUN_INITIALIZE:
554 {
555 HashSet<String> queue;
556
557 // Snapshot the pending-init queue and work on that
558 synchronized (mQueueLock) {
559 queue = new HashSet<String>(mPendingInits);
560 mPendingInits.clear();
561 }
562
563 (new PerformInitializeTask(queue)).run();
564 break;
565 }
566
Christopher Tate2d449afe2010-03-29 19:14:24 -0700567 case MSG_RUN_GET_RESTORE_SETS:
568 {
569 // Like other async operations, this is entered with the wakelock held
570 RestoreSet[] sets = null;
571 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
572 try {
573 sets = params.transport.getAvailableRestoreSets();
574 // cache the result in the active session
575 synchronized (params.session) {
576 params.session.mRestoreSets = sets;
577 }
578 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
579 } catch (Exception e) {
580 Slog.e(TAG, "Error from transport getting set list");
581 } finally {
582 if (params.observer != null) {
583 try {
584 params.observer.restoreSetsAvailable(sets);
585 } catch (RemoteException re) {
586 Slog.e(TAG, "Unable to report listing to observer");
587 } catch (Exception e) {
588 Slog.e(TAG, "Restore observer threw", e);
589 }
590 }
591
Christopher Tate2a935092011-03-03 17:30:32 -0800592 // Done: reset the session timeout clock
593 removeMessages(MSG_RESTORE_TIMEOUT);
594 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
595
Christopher Tate2d449afe2010-03-29 19:14:24 -0700596 mWakelock.release();
597 }
598 break;
599 }
600
Christopher Tate44a27902010-01-27 17:15:49 -0800601 case MSG_TIMEOUT:
602 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700603 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800604 break;
605 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800606
607 case MSG_RESTORE_TIMEOUT:
608 {
609 synchronized (BackupManagerService.this) {
610 if (mActiveRestoreSession != null) {
611 // Client app left the restore session dangling. We know that it
612 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700613 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800614 // up now.
615 Slog.w(TAG, "Restore session timed out; aborting");
616 post(mActiveRestoreSession.new EndRestoreRunnable(
617 BackupManagerService.this, mActiveRestoreSession));
618 }
619 }
620 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700621
622 case MSG_FULL_CONFIRMATION_TIMEOUT:
623 {
624 synchronized (mFullConfirmations) {
625 FullParams params = mFullConfirmations.get(msg.arg1);
626 if (params != null) {
627 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
628
629 // Release the waiter; timeout == completion
630 signalFullBackupRestoreCompletion(params);
631
632 // Remove the token from the set
633 mFullConfirmations.delete(msg.arg1);
634
635 // Report a timeout to the observer, if any
636 if (params.observer != null) {
637 try {
638 params.observer.onTimeout();
639 } catch (RemoteException e) {
640 /* don't care if the app has gone away */
641 }
642 }
643 } else {
644 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
645 }
646 }
647 break;
648 }
Christopher Tate44a27902010-01-27 17:15:49 -0800649 }
650 }
651 }
652
653 // ----- Main service implementation -----
654
Christopher Tate487529a2009-04-29 14:03:25 -0700655 public BackupManagerService(Context context) {
656 mContext = context;
657 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700658 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700659 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700660
Christopher Tateb6787f22009-07-02 17:40:45 -0700661 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
662 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
663
Christopher Tate44a27902010-01-27 17:15:49 -0800664 mBackupManagerBinder = asInterface(asBinder());
665
666 // spin up the backup/restore handler thread
667 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
668 mHandlerThread.start();
669 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
670
Christopher Tate22b87872009-05-04 16:41:53 -0700671 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700672 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700673 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700674 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700675 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800676 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800677 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800678 // If Encrypted file systems is enabled or disabled, this call will return the
679 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600680 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800681 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700682 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700683
Christopher Tate2efd2db2011-07-19 16:32:49 -0700684 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
685 if (mPasswordHashFile.exists()) {
686 FileInputStream fin = null;
687 DataInputStream in = null;
688 try {
689 fin = new FileInputStream(mPasswordHashFile);
690 in = new DataInputStream(new BufferedInputStream(fin));
691 // integer length of the salt array, followed by the salt,
692 // then the hex pw hash string
693 int saltLen = in.readInt();
694 byte[] salt = new byte[saltLen];
695 in.readFully(salt);
696 mPasswordHash = in.readUTF();
697 mPasswordSalt = salt;
698 } catch (IOException e) {
699 Slog.e(TAG, "Unable to read saved backup pw hash");
700 } finally {
701 try {
702 if (in != null) in.close();
703 if (fin != null) fin.close();
704 } catch (IOException e) {
705 Slog.w(TAG, "Unable to close streams");
706 }
707 }
708 }
709
Christopher Tate4cc86e12009-09-21 19:36:51 -0700710 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700711 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700712 IntentFilter filter = new IntentFilter();
713 filter.addAction(RUN_BACKUP_ACTION);
714 context.registerReceiver(mRunBackupReceiver, filter,
715 android.Manifest.permission.BACKUP, null);
716
717 mRunInitReceiver = new RunInitializeReceiver();
718 filter = new IntentFilter();
719 filter.addAction(RUN_INITIALIZE_ACTION);
720 context.registerReceiver(mRunInitReceiver, filter,
721 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700722
723 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700724 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
725 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
726
Christopher Tate4cc86e12009-09-21 19:36:51 -0700727 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
728 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
729 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
730
Christopher Tatecde87f42009-06-12 12:55:53 -0700731 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700732 mJournalDir = new File(mBaseStateDir, "pending");
733 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700734 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700735
Christopher Tate73e02522009-07-15 14:18:26 -0700736 // Set up the various sorts of package tracking we do
737 initPackageTracking();
738
Christopher Tateabce4e82009-06-18 18:35:32 -0700739 // Build our mapping of uid to backup client services. This implicitly
740 // schedules a backup pass on the Package Manager metadata the first
741 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700742 synchronized (mBackupParticipants) {
743 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700744 }
745
Dan Egnor87a02bc2009-06-17 02:30:10 -0700746 // Set up our transport options and initialize the default transport
747 // TODO: Have transports register themselves somehow?
748 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700749 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700750 ComponentName localName = new ComponentName(context, LocalTransport.class);
751 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700752
Christopher Tate91717492009-06-26 21:07:13 -0700753 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700754 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
755 Settings.Secure.BACKUP_TRANSPORT);
756 if ("".equals(mCurrentTransport)) {
757 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700758 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800759 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700760
761 // Attach to the Google backup transport. When this comes up, it will set
762 // itself as the current transport because we explicitly reset mCurrentTransport
763 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700764 ComponentName transportComponent = new ComponentName("com.google.android.backup",
765 "com.google.android.backup.BackupTransportService");
766 try {
767 // If there's something out there that is supposed to be the Google
768 // backup transport, make sure it's legitimately part of the OS build
769 // and not an app lying about its package name.
770 ApplicationInfo info = mPackageManager.getApplicationInfo(
771 transportComponent.getPackageName(), 0);
772 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
773 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
774 Intent intent = new Intent().setComponent(transportComponent);
775 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
776 } else {
777 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
778 }
779 } catch (PackageManager.NameNotFoundException nnf) {
780 // No such package? No binding.
781 if (DEBUG) Slog.v(TAG, "Google transport not present");
782 }
Christopher Tateaa088442009-06-16 18:25:46 -0700783
Christopher Tatecde87f42009-06-12 12:55:53 -0700784 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700785 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700786 parseLeftoverJournals();
787
Christopher Tateb6787f22009-07-02 17:40:45 -0700788 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700789 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700790
791 // Start the backup passes going
792 setBackupEnabled(areEnabled);
793 }
794
795 private class RunBackupReceiver extends BroadcastReceiver {
796 public void onReceive(Context context, Intent intent) {
797 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700798 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700799 if (mPendingInits.size() > 0) {
800 // If there are pending init operations, we process those
801 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800802 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700803 try {
804 mAlarmManager.cancel(mRunInitIntent);
805 mRunInitIntent.send();
806 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800807 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700808 // can't really do more than bail here
809 }
810 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800811 // Don't run backups now if we're disabled or not yet
812 // fully set up.
813 if (mEnabled && mProvisioned) {
Christopher Tate336a6492011-10-05 16:05:43 -0700814 if (!mBackupRunning) {
815 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700816
Christopher Tate336a6492011-10-05 16:05:43 -0700817 // Acquire the wakelock and pass it to the backup thread. it will
818 // be released once backup concludes.
819 mBackupRunning = true;
820 mWakelock.acquire();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700821
Christopher Tate336a6492011-10-05 16:05:43 -0700822 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
823 mBackupHandler.sendMessage(msg);
824 } else {
825 Slog.i(TAG, "Backup time but one already running");
826 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700827 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800828 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700829 }
830 }
831 }
832 }
833 }
834 }
835
836 private class RunInitializeReceiver extends BroadcastReceiver {
837 public void onReceive(Context context, Intent intent) {
838 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
839 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800840 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700841
842 // Acquire the wakelock and pass it to the init thread. it will
843 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700844 mWakelock.acquire();
845
Christopher Tate4cc86e12009-09-21 19:36:51 -0700846 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700847 mBackupHandler.sendMessage(msg);
848 }
849 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700850 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700851 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700852
Christopher Tate73e02522009-07-15 14:18:26 -0700853 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800854 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700855
Christopher Tate84725812010-02-04 15:52:40 -0800856 // Remember our ancestral dataset
857 mTokenFile = new File(mBaseStateDir, "ancestral");
858 try {
859 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800860 int version = tf.readInt();
861 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
862 mAncestralToken = tf.readLong();
863 mCurrentToken = tf.readLong();
864
865 int numPackages = tf.readInt();
866 if (numPackages >= 0) {
867 mAncestralPackages = new HashSet<String>();
868 for (int i = 0; i < numPackages; i++) {
869 String pkgName = tf.readUTF();
870 mAncestralPackages.add(pkgName);
871 }
872 }
873 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800874 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800875 } catch (FileNotFoundException fnf) {
876 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800877 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800878 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800879 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800880 }
881
Christopher Tatee97e8072009-07-15 16:45:50 -0700882 // Keep a log of what apps we've ever backed up. Because we might have
883 // rebooted in the middle of an operation that was removing something from
884 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700885 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700886 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700887
Christopher Tatee97e8072009-07-15 16:45:50 -0700888 // If we were in the middle of removing something from the ever-backed-up
889 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700890 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700891 if (tempProcessedFile.exists()) {
892 tempProcessedFile.delete();
893 }
894
Dan Egnor852f8e42009-09-30 11:20:45 -0700895 // If there are previous contents, parse them out then start a new
896 // file to continue the recordkeeping.
897 if (mEverStored.exists()) {
898 RandomAccessFile temp = null;
899 RandomAccessFile in = null;
900
901 try {
902 temp = new RandomAccessFile(tempProcessedFile, "rws");
903 in = new RandomAccessFile(mEverStored, "r");
904
905 while (true) {
906 PackageInfo info;
907 String pkg = in.readUTF();
908 try {
909 info = mPackageManager.getPackageInfo(pkg, 0);
910 mEverStoredApps.add(pkg);
911 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700912 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700913 } catch (NameNotFoundException e) {
914 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700915 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700916 }
917 }
918 } catch (EOFException e) {
919 // Once we've rewritten the backup history log, atomically replace the
920 // old one with the new one then reopen the file for continuing use.
921 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800922 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700923 }
924 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800925 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700926 } finally {
927 try { if (temp != null) temp.close(); } catch (IOException e) {}
928 try { if (in != null) in.close(); } catch (IOException e) {}
929 }
930 }
931
Christopher Tate73e02522009-07-15 14:18:26 -0700932 // Register for broadcasts about package install, etc., so we can
933 // update the provider list.
934 IntentFilter filter = new IntentFilter();
935 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
936 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700937 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700938 filter.addDataScheme("package");
939 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800940 // Register for events related to sdcard installation.
941 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800942 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
943 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800944 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700945 }
946
Christopher Tatecde87f42009-06-12 12:55:53 -0700947 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700948 for (File f : mJournalDir.listFiles()) {
949 if (mJournal == null || f.compareTo(mJournal) != 0) {
950 // This isn't the current journal, so it must be a leftover. Read
951 // out the package names mentioned there and schedule them for
952 // backup.
953 RandomAccessFile in = null;
954 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400955 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700956 in = new RandomAccessFile(f, "r");
957 while (true) {
958 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400959 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700960 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700961 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700962 } catch (EOFException e) {
963 // no more data; we're done
964 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800965 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700966 } finally {
967 // close/delete the file
968 try { if (in != null) in.close(); } catch (IOException e) {}
969 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700970 }
971 }
972 }
973 }
974
Christopher Tate2efd2db2011-07-19 16:32:49 -0700975 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
976 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
977 }
978
979 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
980 try {
981 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
982 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
983 return keyFactory.generateSecret(ks);
984 } catch (InvalidKeySpecException e) {
985 Slog.e(TAG, "Invalid key spec for PBKDF2!");
986 } catch (NoSuchAlgorithmException e) {
987 Slog.e(TAG, "PBKDF2 unavailable!");
988 }
989 return null;
990 }
991
992 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
993 SecretKey key = buildPasswordKey(pw, salt, rounds);
994 if (key != null) {
995 return byteArrayToHex(key.getEncoded());
996 }
997 return null;
998 }
999
1000 private String byteArrayToHex(byte[] data) {
1001 StringBuilder buf = new StringBuilder(data.length * 2);
1002 for (int i = 0; i < data.length; i++) {
1003 buf.append(Byte.toHexString(data[i], true));
1004 }
1005 return buf.toString();
1006 }
1007
1008 private byte[] hexToByteArray(String digits) {
1009 final int bytes = digits.length() / 2;
1010 if (2*bytes != digits.length()) {
1011 throw new IllegalArgumentException("Hex string must have an even number of digits");
1012 }
1013
1014 byte[] result = new byte[bytes];
1015 for (int i = 0; i < digits.length(); i += 2) {
1016 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1017 }
1018 return result;
1019 }
1020
1021 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1022 char[] mkAsChar = new char[pwBytes.length];
1023 for (int i = 0; i < pwBytes.length; i++) {
1024 mkAsChar[i] = (char) pwBytes[i];
1025 }
1026
1027 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1028 return checksum.getEncoded();
1029 }
1030
1031 // Used for generating random salts or passwords
1032 private byte[] randomBytes(int bits) {
1033 byte[] array = new byte[bits / 8];
1034 mRng.nextBytes(array);
1035 return array;
1036 }
1037
1038 // Backup password management
1039 boolean passwordMatchesSaved(String candidatePw, int rounds) {
1040 if (mPasswordHash == null) {
1041 // no current password case -- require that 'currentPw' be null or empty
1042 if (candidatePw == null || "".equals(candidatePw)) {
1043 return true;
1044 } // else the non-empty candidate does not match the empty stored pw
1045 } else {
1046 // hash the stated current pw and compare to the stored one
1047 if (candidatePw != null && candidatePw.length() > 0) {
1048 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1049 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1050 // candidate hash matches the stored hash -- the password matches
1051 return true;
1052 }
1053 } // else the stored pw is nonempty but the candidate is empty; no match
1054 }
1055 return false;
1056 }
1057
1058 @Override
1059 public boolean setBackupPassword(String currentPw, String newPw) {
1060 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1061 "setBackupPassword");
1062
1063 // If the supplied pw doesn't hash to the the saved one, fail
1064 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1065 return false;
1066 }
1067
1068 // Clearing the password is okay
1069 if (newPw == null || newPw.isEmpty()) {
1070 if (mPasswordHashFile.exists()) {
1071 if (!mPasswordHashFile.delete()) {
1072 // Unable to delete the old pw file, so fail
1073 Slog.e(TAG, "Unable to clear backup password");
1074 return false;
1075 }
1076 }
1077 mPasswordHash = null;
1078 mPasswordSalt = null;
1079 return true;
1080 }
1081
1082 try {
1083 // Okay, build the hash of the new backup password
1084 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1085 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1086
1087 OutputStream pwf = null, buffer = null;
1088 DataOutputStream out = null;
1089 try {
1090 pwf = new FileOutputStream(mPasswordHashFile);
1091 buffer = new BufferedOutputStream(pwf);
1092 out = new DataOutputStream(buffer);
1093 // integer length of the salt array, followed by the salt,
1094 // then the hex pw hash string
1095 out.writeInt(salt.length);
1096 out.write(salt);
1097 out.writeUTF(newPwHash);
1098 out.flush();
1099 mPasswordHash = newPwHash;
1100 mPasswordSalt = salt;
1101 return true;
1102 } finally {
1103 if (out != null) out.close();
1104 if (buffer != null) buffer.close();
1105 if (pwf != null) pwf.close();
1106 }
1107 } catch (IOException e) {
1108 Slog.e(TAG, "Unable to set backup password");
1109 }
1110 return false;
1111 }
1112
1113 @Override
1114 public boolean hasBackupPassword() {
1115 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1116 "hasBackupPassword");
1117 return (mPasswordHash != null && mPasswordHash.length() > 0);
1118 }
1119
Christopher Tate4cc86e12009-09-21 19:36:51 -07001120 // Maintain persistent state around whether need to do an initialize operation.
1121 // Must be called with the queue lock held.
1122 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001123 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001124 + " on transport " + transportName);
1125 try {
1126 IBackupTransport transport = getTransport(transportName);
1127 String transportDirName = transport.transportDirName();
1128 File stateDir = new File(mBaseStateDir, transportDirName);
1129 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1130
1131 if (isPending) {
1132 // We need an init before we can proceed with sending backup data.
1133 // Record that with an entry in our set of pending inits, as well as
1134 // journaling it via creation of a sentinel file.
1135 mPendingInits.add(transportName);
1136 try {
1137 (new FileOutputStream(initPendingFile)).close();
1138 } catch (IOException ioe) {
1139 // Something is badly wrong with our permissions; just try to move on
1140 }
1141 } else {
1142 // No more initialization needed; wipe the journal and reset our state.
1143 initPendingFile.delete();
1144 mPendingInits.remove(transportName);
1145 }
1146 } catch (RemoteException e) {
1147 // can't happen; the transport is local
1148 }
1149 }
1150
Christopher Tated55e18a2009-09-21 10:12:59 -07001151 // Reset all of our bookkeeping, in response to having been told that
1152 // the backend data has been wiped [due to idle expiry, for example],
1153 // so we must re-upload all saved settings.
1154 void resetBackupState(File stateFileDir) {
1155 synchronized (mQueueLock) {
1156 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001157 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001158 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001159
Christopher Tate84725812010-02-04 15:52:40 -08001160 mCurrentToken = 0;
1161 writeRestoreTokens();
1162
Christopher Tated55e18a2009-09-21 10:12:59 -07001163 // Remove all the state files
1164 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001165 // ... but don't touch the needs-init sentinel
1166 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1167 sf.delete();
1168 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001169 }
Christopher Tate45597642011-04-04 16:59:21 -07001170 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001171
Christopher Tate45597642011-04-04 16:59:21 -07001172 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001173 synchronized (mBackupParticipants) {
1174 int N = mBackupParticipants.size();
1175 for (int i=0; i<N; i++) {
1176 int uid = mBackupParticipants.keyAt(i);
1177 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1178 for (ApplicationInfo app: participants) {
1179 dataChangedImpl(app.packageName);
1180 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001181 }
1182 }
1183 }
1184
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001185 // Add a transport to our set of available backends. If 'transport' is null, this
1186 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001187 private void registerTransport(String name, IBackupTransport transport) {
1188 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001189 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001190 if (transport != null) {
1191 mTransports.put(name, transport);
1192 } else {
1193 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001194 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001195 mCurrentTransport = null;
1196 }
1197 // Nothing further to do in the unregistration case
1198 return;
1199 }
Christopher Tate91717492009-06-26 21:07:13 -07001200 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001201
1202 // If the init sentinel file exists, we need to be sure to perform the init
1203 // as soon as practical. We also create the state directory at registration
1204 // time to ensure it's present from the outset.
1205 try {
1206 String transportName = transport.transportDirName();
1207 File stateDir = new File(mBaseStateDir, transportName);
1208 stateDir.mkdirs();
1209
1210 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1211 if (initSentinel.exists()) {
1212 synchronized (mQueueLock) {
1213 mPendingInits.add(transportName);
1214
1215 // TODO: pick a better starting time than now + 1 minute
1216 long delay = 1000 * 60; // one minute, in milliseconds
1217 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1218 System.currentTimeMillis() + delay, mRunInitIntent);
1219 }
1220 }
1221 } catch (RemoteException e) {
1222 // can't happen, the transport is local
1223 }
Christopher Tate91717492009-06-26 21:07:13 -07001224 }
1225
Christopher Tate3799bc22009-05-06 16:13:56 -07001226 // ----- Track installation/removal of packages -----
1227 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1228 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001229 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001230
Christopher Tate3799bc22009-05-06 16:13:56 -07001231 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001232 boolean replacing = false;
1233 boolean added = false;
1234 Bundle extras = intent.getExtras();
1235 String pkgList[] = null;
1236 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001237 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1238 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001239 Uri uri = intent.getData();
1240 if (uri == null) {
1241 return;
1242 }
1243 String pkgName = uri.getSchemeSpecificPart();
1244 if (pkgName != null) {
1245 pkgList = new String[] { pkgName };
1246 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001247 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1248 // use the existing "add with replacement" logic
1249 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1250 added = replacing = true;
1251 } else {
1252 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1253 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1254 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001255 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001256 added = true;
1257 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001258 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001259 added = false;
1260 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1261 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001262
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001263 if (pkgList == null || pkgList.length == 0) {
1264 return;
1265 }
1266 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001267 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001268 for (String pkgName : pkgList) {
1269 if (replacing) {
1270 // The package was just upgraded
1271 updatePackageParticipantsLocked(pkgName);
1272 } else {
1273 // The package was just added
1274 addPackageParticipantsLocked(pkgName);
1275 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001276 }
1277 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001278 } else {
1279 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001280 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1281 } else {
1282 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001283 for (String pkgName : pkgList) {
1284 removePackageParticipantsLocked(pkgName);
1285 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001286 }
1287 }
1288 }
1289 }
1290 };
1291
Dan Egnor87a02bc2009-06-17 02:30:10 -07001292 // ----- Track connection to GoogleBackupTransport service -----
1293 ServiceConnection mGoogleConnection = new ServiceConnection() {
1294 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001295 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001296 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001297 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001298 }
1299
1300 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001301 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001302 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001303 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001304 }
1305 };
1306
Christopher Tate181fafa2009-05-14 11:12:14 -07001307 // Add the backup agents in the given package to our set of known backup participants.
1308 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001309 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001310 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001311 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001312 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001313 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001314 }
1315
Christopher Tate181fafa2009-05-14 11:12:14 -07001316 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001317 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001318 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001319 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001320 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001321 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001322 + " uid=" + p.applicationInfo.uid
1323 + " killAfterRestore="
1324 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001325 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001326 }
1327 }
1328
Dan Egnorefe52642009-06-24 00:16:33 -07001329 for (PackageInfo pkg : targetPkgs) {
1330 if (packageName == null || pkg.packageName.equals(packageName)) {
1331 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001332 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001333 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001334 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001335 mBackupParticipants.put(uid, set);
1336 }
Dan Egnorefe52642009-06-24 00:16:33 -07001337 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001338
1339 // If we've never seen this app before, schedule a backup for it
1340 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001341 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001342 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001343 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001344 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001345 }
Christopher Tate487529a2009-04-29 14:03:25 -07001346 }
1347 }
1348
Christopher Tate6785dd82009-06-18 15:58:25 -07001349 // Remove the given package's entry from our known active set. If
1350 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001351 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001352 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001353 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001354 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001355 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001356 } else {
1357 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001358 List<PackageInfo> knownPackages = allAgentPackages();
1359 for (PackageInfo pkg : knownPackages) {
1360 allApps.add(pkg.packageName);
1361 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001362 }
1363 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001364 }
1365
Joe Onorato8ad02812009-05-13 01:41:44 -04001366 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001367 List<String> allPackageNames) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001368 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001369 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001370 + ") removing " + allPackageNames.size() + " entries");
1371 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001372 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001373 }
1374 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001375 for (String pkg : allPackageNames) {
1376 if (packageName == null || pkg.equals(packageName)) {
1377 int uid = -1;
1378 try {
1379 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1380 uid = info.applicationInfo.uid;
1381 } catch (NameNotFoundException e) {
1382 // we don't know this package name, so just skip it for now
1383 continue;
1384 }
1385
Christopher Tate181fafa2009-05-14 11:12:14 -07001386 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001387 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001388 // Find the existing entry with the same package name, and remove it.
1389 // We can't just remove(app) because the instances are different.
1390 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001391 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001392 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001393 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001394 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001395 break;
1396 }
1397 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001398 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001399 mBackupParticipants.delete(uid);
1400 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001401 }
1402 }
1403 }
1404 }
1405
Christopher Tate181fafa2009-05-14 11:12:14 -07001406 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001407 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001408 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001409 int flags = PackageManager.GET_SIGNATURES;
1410 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1411 int N = packages.size();
1412 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001413 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001414 try {
1415 ApplicationInfo app = pkg.applicationInfo;
1416 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001417 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001418 packages.remove(a);
1419 }
1420 else {
1421 // we will need the shared library path, so look that up and store it here
1422 app = mPackageManager.getApplicationInfo(pkg.packageName,
1423 PackageManager.GET_SHARED_LIBRARY_FILES);
1424 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1425 }
1426 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001427 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001428 }
1429 }
Dan Egnorefe52642009-06-24 00:16:33 -07001430 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001431 }
Christopher Tateaa088442009-06-16 18:25:46 -07001432
Christopher Tate3799bc22009-05-06 16:13:56 -07001433 // Reset the given package's known backup participants. Unlike add/remove, the update
1434 // action cannot be passed a null package name.
1435 void updatePackageParticipantsLocked(String packageName) {
1436 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001437 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001438 return;
1439 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001440 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001441
1442 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001443 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001444 List<String> allAppNames = new ArrayList<String>();
1445 for (PackageInfo pkg : allApps) {
1446 allAppNames.add(pkg.packageName);
1447 }
1448 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001449 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001450 }
1451
Christopher Tate84725812010-02-04 15:52:40 -08001452 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001453 // backed up at least once
1454 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001455 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1456
1457 synchronized (mEverStoredApps) {
1458 if (!mEverStoredApps.add(packageName)) return;
1459
1460 RandomAccessFile out = null;
1461 try {
1462 out = new RandomAccessFile(mEverStored, "rws");
1463 out.seek(out.length());
1464 out.writeUTF(packageName);
1465 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001466 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001467 } finally {
1468 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001469 }
1470 }
1471 }
1472
Christopher Tatee97e8072009-07-15 16:45:50 -07001473 // Remove our awareness of having ever backed up the given package
1474 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001475 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1476 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001477
Dan Egnor852f8e42009-09-30 11:20:45 -07001478 synchronized (mEverStoredApps) {
1479 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1480 // we'll recognize on initialization time that the package no longer
1481 // exists and fix it up then.
1482 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1483 RandomAccessFile known = null;
1484 try {
1485 known = new RandomAccessFile(tempKnownFile, "rws");
1486 mEverStoredApps.remove(packageName);
1487 for (String s : mEverStoredApps) {
1488 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001489 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001490 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001491 known.close();
1492 known = null;
1493 if (!tempKnownFile.renameTo(mEverStored)) {
1494 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1495 }
1496 } catch (IOException e) {
1497 // Bad: we couldn't create the new copy. For safety's sake we
1498 // abandon the whole process and remove all what's-backed-up
1499 // state entirely, meaning we'll force a backup pass for every
1500 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001502 mEverStoredApps.clear();
1503 tempKnownFile.delete();
1504 mEverStored.delete();
1505 } finally {
1506 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001507 }
1508 }
1509 }
1510
Christopher Tateb49ceb32010-02-08 16:22:24 -08001511 // Persistently record the current and ancestral backup tokens as well
1512 // as the set of packages with data [supposedly] available in the
1513 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001514 void writeRestoreTokens() {
1515 try {
1516 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001517
1518 // First, the version number of this record, for futureproofing
1519 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1520
1521 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001522 af.writeLong(mAncestralToken);
1523 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001524
1525 // Now write the set of ancestral packages
1526 if (mAncestralPackages == null) {
1527 af.writeInt(-1);
1528 } else {
1529 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001530 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001531 for (String pkgName : mAncestralPackages) {
1532 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001533 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001534 }
1535 }
Christopher Tate84725812010-02-04 15:52:40 -08001536 af.close();
1537 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001538 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001539 }
1540 }
1541
Dan Egnor87a02bc2009-06-17 02:30:10 -07001542 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001543 private IBackupTransport getTransport(String transportName) {
1544 synchronized (mTransports) {
1545 IBackupTransport transport = mTransports.get(transportName);
1546 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001547 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001548 }
1549 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001550 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001551 }
1552
Christopher Tatedf01dea2009-06-09 20:45:02 -07001553 // fire off a backup agent, blocking until it attaches or times out
1554 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1555 IBackupAgent agent = null;
1556 synchronized(mAgentConnectLock) {
1557 mConnecting = true;
1558 mConnectedAgent = null;
1559 try {
1560 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001561 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001562
1563 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001564 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001565 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1566 while (mConnecting && mConnectedAgent == null
1567 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001568 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001569 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001570 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001571 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001572 return null;
1573 }
1574 }
1575
1576 // if we timed out with no connect, abort and move on
1577 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001578 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001579 return null;
1580 }
1581 agent = mConnectedAgent;
1582 }
1583 } catch (RemoteException e) {
1584 // can't happen
1585 }
1586 }
1587 return agent;
1588 }
1589
Christopher Tatec7b31e32009-06-10 15:49:30 -07001590 // clear an application's data, blocking until the operation completes or times out
1591 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001592 // Don't wipe packages marked allowClearUserData=false
1593 try {
1594 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1595 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001596 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001597 + packageName);
1598 return;
1599 }
1600 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001602 return;
1603 }
1604
Christopher Tatec7b31e32009-06-10 15:49:30 -07001605 ClearDataObserver observer = new ClearDataObserver();
1606
1607 synchronized(mClearDataLock) {
1608 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001609 try {
1610 mActivityManager.clearApplicationUserData(packageName, observer);
1611 } catch (RemoteException e) {
1612 // can't happen because the activity manager is in this process
1613 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001614
1615 // only wait 10 seconds for the clear data to happen
1616 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1617 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1618 try {
1619 mClearDataLock.wait(5000);
1620 } catch (InterruptedException e) {
1621 // won't happen, but still.
1622 mClearingData = false;
1623 }
1624 }
1625 }
1626 }
1627
1628 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001629 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001630 synchronized(mClearDataLock) {
1631 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001632 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001633 }
1634 }
1635 }
1636
Christopher Tate1bb69062010-02-19 17:02:12 -08001637 // Get the restore-set token for the best-available restore set for this package:
1638 // the active set if possible, else the ancestral one. Returns zero if none available.
1639 long getAvailableRestoreToken(String packageName) {
1640 long token = mAncestralToken;
1641 synchronized (mQueueLock) {
1642 if (mEverStoredApps.contains(packageName)) {
1643 token = mCurrentToken;
1644 }
1645 }
1646 return token;
1647 }
1648
Christopher Tate44a27902010-01-27 17:15:49 -08001649 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001650 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1651
1652 interface BackupRestoreTask {
1653 // Execute one tick of whatever state machine the task implements
1654 void execute();
1655
1656 // An operation that wanted a callback has completed
1657 void operationComplete();
1658
1659 // An operation that wanted a callback has timed out
1660 void handleTimeout();
1661 }
1662
1663 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1664 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1665 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001666 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001667 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1668
1669 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1670 mBackupHandler.sendMessageDelayed(msg, interval);
1671 }
1672 }
1673
1674 // synchronous waiter case
1675 boolean waitUntilOperationComplete(int token) {
1676 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1677 + Integer.toHexString(token));
1678 int finalState = OP_PENDING;
1679 Operation op = null;
1680 synchronized (mCurrentOpLock) {
1681 while (true) {
1682 op = mCurrentOperations.get(token);
1683 if (op == null) {
1684 // mysterious disappearance: treat as success with no callback
1685 break;
1686 } else {
1687 if (op.state == OP_PENDING) {
1688 try {
1689 mCurrentOpLock.wait();
1690 } catch (InterruptedException e) {}
1691 // When the wait is notified we loop around and recheck the current state
1692 } else {
1693 // No longer pending; we're done
1694 finalState = op.state;
1695 break;
1696 }
Christopher Tate44a27902010-01-27 17:15:49 -08001697 }
Christopher Tate44a27902010-01-27 17:15:49 -08001698 }
1699 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001700
Christopher Tate44a27902010-01-27 17:15:49 -08001701 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001702 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001703 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001704 return finalState == OP_ACKNOWLEDGED;
1705 }
1706
Christopher Tate8e294d42011-08-31 20:37:12 -07001707 void handleTimeout(int token, Object obj) {
1708 // Notify any synchronous waiters
1709 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001710 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001711 op = mCurrentOperations.get(token);
1712 if (MORE_DEBUG) {
1713 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1714 + " but no op found");
1715 }
1716 int state = (op != null) ? op.state : OP_TIMEOUT;
1717 if (state == OP_PENDING) {
1718 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1719 op.state = OP_TIMEOUT;
1720 mCurrentOperations.put(token, op);
1721 }
1722 mCurrentOpLock.notifyAll();
1723 }
1724
1725 // If there's a TimeoutHandler for this event, call it
1726 if (op != null && op.callback != null) {
1727 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001728 }
Christopher Tate44a27902010-01-27 17:15:49 -08001729 }
1730
Christopher Tate043dadc2009-06-02 16:11:00 -07001731 // ----- Back up a set of applications via a worker thread -----
1732
Christopher Tate8e294d42011-08-31 20:37:12 -07001733 enum BackupState {
1734 INITIAL,
1735 RUNNING_QUEUE,
1736 FINAL
1737 }
1738
1739 class PerformBackupTask implements BackupRestoreTask {
1740 private static final String TAG = "PerformBackupTask";
1741
Christopher Tateaa088442009-06-16 18:25:46 -07001742 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001743 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001744 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001745 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001746 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001747 BackupState mCurrentState;
1748
1749 // carried information about the current in-flight operation
1750 PackageInfo mCurrentPackage;
1751 File mSavedStateName;
1752 File mBackupDataName;
1753 File mNewStateName;
1754 ParcelFileDescriptor mSavedState;
1755 ParcelFileDescriptor mBackupData;
1756 ParcelFileDescriptor mNewState;
1757 int mStatus;
1758 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001759
Christopher Tate44a27902010-01-27 17:15:49 -08001760 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001761 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001762 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001763 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001764 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001765
1766 try {
1767 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1768 } catch (RemoteException e) {
1769 // can't happen; the transport is local
1770 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001771
1772 mCurrentState = BackupState.INITIAL;
1773 mFinished = false;
Christopher Tate043dadc2009-06-02 16:11:00 -07001774 }
1775
Christopher Tate8e294d42011-08-31 20:37:12 -07001776 // Main entry point: perform one chunk of work, updating the state as appropriate
1777 // and reposting the next chunk to the primary backup handler thread.
1778 @Override
1779 public void execute() {
1780 switch (mCurrentState) {
1781 case INITIAL:
1782 beginBackup();
1783 break;
1784
1785 case RUNNING_QUEUE:
1786 invokeNextAgent();
1787 break;
1788
1789 case FINAL:
1790 if (!mFinished) finalizeBackup();
1791 else {
1792 Slog.e(TAG, "Duplicate finish");
1793 }
Christopher Tate2982d062011-09-06 20:35:24 -07001794 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001795 break;
1796 }
1797 }
1798
1799 // We're starting a backup pass. Initialize the transport and send
1800 // the PM metadata blob if we haven't already.
1801 void beginBackup() {
1802 mStatus = BackupConstants.TRANSPORT_OK;
1803
1804 // Sanity check: if the queue is empty we have no work to do.
1805 if (mOriginalQueue.isEmpty()) {
1806 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
1807 return;
1808 }
1809
1810 // We need to retain the original queue contents in case of transport
1811 // failure, but we want a working copy that we can manipulate along
1812 // the way.
1813 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1814
Joe Onorato8a9b2202010-02-26 18:56:32 -08001815 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001816
Christopher Tate8e294d42011-08-31 20:37:12 -07001817 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001818 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001819 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001820
Dan Egnor852f8e42009-09-30 11:20:45 -07001821 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001822 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001823 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001824 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001825 mStatus = mTransport.initializeDevice();
1826 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001827 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001828 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001829 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001830 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001831 }
Dan Egnor01445162009-09-21 17:04:05 -07001832 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001833
1834 // The package manager doesn't have a proper <application> etc, but since
1835 // it's running here in the system process we can just set up its agent
1836 // directly and use a synthetic BackupRequest. We always run this pass
1837 // because it's cheap and this way we guarantee that we don't get out of
1838 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001839 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001840 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1841 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001842 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001843 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1844 }
Christopher Tate90967f42009-09-20 15:28:33 -07001845
Christopher Tate8e294d42011-08-31 20:37:12 -07001846 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1847 // The backend reports that our dataset has been wiped. Note this in
1848 // the event log; the no-success code below will reset the backup
1849 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001850 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001851 }
1852 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001853 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001854 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001855 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001856 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1857 // metadata and its completion/timeout callback will continue the state
1858 // machine chain. If it failed that won't happen; we handle that now.
1859 if (mStatus != BackupConstants.TRANSPORT_OK) {
1860 // if things went wrong at this point, we need to
1861 // restage everything and try again later.
1862 resetBackupState(mStateDir); // Just to make sure.
1863 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001864 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001865 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001866 }
1867
Christopher Tate8e294d42011-08-31 20:37:12 -07001868 // Transport has been initialized and the PM metadata submitted successfully
1869 // if that was warranted. Now we process the single next thing in the queue.
1870 void invokeNextAgent() {
1871 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001872
Christopher Tate8e294d42011-08-31 20:37:12 -07001873 // Sanity check that we have work to do. If not, skip to the end where
1874 // we reestablish the wakelock invariants etc.
1875 if (mQueue.isEmpty()) {
1876 Slog.e(TAG, "Running queue but it's empty!");
1877 executeNextState(BackupState.FINAL);
1878 return;
1879 }
1880
1881 // pop the entry we're going to process on this step
1882 BackupRequest request = mQueue.get(0);
1883 mQueue.remove(0);
1884
1885 Slog.d(TAG, "starting agent for backup of " + request);
1886
1887 // Verify that the requested app exists; it might be something that
1888 // requested a backup but was then uninstalled. The request was
1889 // journalled and rather than tamper with the journal it's safer
1890 // to sanity-check here. This also gives us the classname of the
1891 // package's backup agent.
1892 try {
1893 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1894 PackageManager.GET_SIGNATURES);
Christopher Tatec28083a2010-12-14 16:16:44 -08001895
Christopher Tate043dadc2009-06-02 16:11:00 -07001896 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001897 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001898 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1899 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001900 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001901 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001902 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1903 // at this point we'll either get a completion callback from the
1904 // agent, or a timeout message on the main handler. either way, we're
1905 // done here as long as we're successful so far.
1906 } else {
1907 // Timeout waiting for the agent
1908 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07001909 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001910 } catch (SecurityException ex) {
1911 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001912 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07001913 mStatus = BackupConstants.AGENT_ERROR;
1914 }
1915 } catch (NameNotFoundException e) {
1916 Slog.d(TAG, "Package does not exist; skipping");
1917 } finally {
1918 mWakelock.setWorkSource(null);
1919
1920 // If there was an agent error, no timeout/completion handling will occur.
1921 // That means we need to deal with the next state ourselves.
1922 if (mStatus != BackupConstants.TRANSPORT_OK) {
1923 BackupState nextState = BackupState.RUNNING_QUEUE;
1924
1925 // An agent-level failure means we reenqueue this one agent for
1926 // a later retry, but otherwise proceed normally.
1927 if (mStatus == BackupConstants.AGENT_ERROR) {
1928 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
1929 + " - restaging");
1930 dataChangedImpl(request.packageName);
1931 mStatus = BackupConstants.TRANSPORT_OK;
1932 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
1933 } else if (mStatus != BackupConstants.TRANSPORT_OK) {
1934 // Transport-level failure means we reenqueue everything
1935 revertAndEndBackup();
1936 nextState = BackupState.FINAL;
1937 }
1938
1939 executeNextState(nextState);
Christopher Tate043dadc2009-06-02 16:11:00 -07001940 }
1941 }
1942 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001943
Christopher Tate8e294d42011-08-31 20:37:12 -07001944 void finalizeBackup() {
1945 // Either backup was successful, in which case we of course do not need
1946 // this pass's journal any more; or it failed, in which case we just
1947 // re-enqueued all of these packages in the current active journal.
1948 // Either way, we no longer need this pass's journal.
1949 if (mJournal != null && !mJournal.delete()) {
1950 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
1951 }
1952
1953 // If everything actually went through and this is the first time we've
1954 // done a backup, we can now record what the current backup dataset token
1955 // is.
1956 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
1957 try {
1958 mCurrentToken = mTransport.getCurrentRestoreSet();
1959 } catch (RemoteException e) {} // can't happen
1960 writeRestoreTokens();
1961 }
1962
Christopher Tate336a6492011-10-05 16:05:43 -07001963 // Set up the next backup pass - at this point we can set mBackupRunning
1964 // to false to allow another pass to fire, because we're done with the
1965 // state machine sequence and the wakelock is refcounted.
1966 synchronized (mQueueLock) {
1967 mBackupRunning = false;
1968 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tatee659fb92011-10-10 16:34:50 -07001969 // Make sure we back up everything and perform the one-time init
1970 clearMetadata();
1971 if (DEBUG) Slog.d(TAG, "Server requires init; rerunning");
Christopher Tate336a6492011-10-05 16:05:43 -07001972 backupNow();
1973 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001974 }
1975
1976 // Only once we're entirely finished do we release the wakelock
1977 Slog.i(TAG, "Backup pass finished.");
1978 mWakelock.release();
1979 }
1980
Christopher Tatee659fb92011-10-10 16:34:50 -07001981 // Remove the PM metadata state. This will generate an init on the next pass.
1982 void clearMetadata() {
1983 final File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1984 if (pmState.exists()) pmState.delete();
1985 }
1986
Christopher Tate8e294d42011-08-31 20:37:12 -07001987 // Invoke an agent's doBackup() and start a timeout message spinning on the main
1988 // handler in case it doesn't get back to us.
1989 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07001990 IBackupTransport transport) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001991 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001992
Christopher Tate8e294d42011-08-31 20:37:12 -07001993 mSavedStateName = new File(mStateDir, packageName);
1994 mBackupDataName = new File(mDataDir, packageName + ".data");
1995 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001996
Christopher Tate8e294d42011-08-31 20:37:12 -07001997 mSavedState = null;
1998 mBackupData = null;
1999 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002000
Christopher Tate4a627c72011-04-01 14:43:32 -07002001 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002002 try {
2003 // Look up the package info & signatures. This is first so that if it
2004 // throws an exception, there's no file setup yet that would need to
2005 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07002006 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002007 // The metadata 'package' is synthetic; construct one and make
2008 // sure our global state is pointed at it
2009 mCurrentPackage = new PackageInfo();
2010 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002011 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002012
Christopher Tatec7b31e32009-06-10 15:49:30 -07002013 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002014 // the saved-state "file". This is by definition an incremental,
2015 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002016 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002017 ParcelFileDescriptor.MODE_READ_ONLY |
2018 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002019
Christopher Tate8e294d42011-08-31 20:37:12 -07002020 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002021 ParcelFileDescriptor.MODE_READ_WRITE |
2022 ParcelFileDescriptor.MODE_CREATE |
2023 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002024
Christopher Tate8e294d42011-08-31 20:37:12 -07002025 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002026 ParcelFileDescriptor.MODE_READ_WRITE |
2027 ParcelFileDescriptor.MODE_CREATE |
2028 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002029
Christopher Tate44a27902010-01-27 17:15:49 -08002030 // Initiate the target's backup pass
Christopher Tate8e294d42011-08-31 20:37:12 -07002031 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
2032 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002033 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002034 Slog.e(TAG, "Error invoking for backup on " + packageName);
2035 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2036 e.toString());
2037 agentErrorCleanup();
2038 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002039 }
2040
Christopher Tate8e294d42011-08-31 20:37:12 -07002041 // At this point the agent is off and running. The next thing to happen will
2042 // either be a callback from the agent, at which point we'll process its data
2043 // for transport, or a timeout. Either way the next phase will happen in
2044 // response to the TimeoutHandler interface callbacks.
2045 return BackupConstants.TRANSPORT_OK;
2046 }
2047
2048 @Override
2049 public void operationComplete() {
2050 // Okay, the agent successfully reported back to us. Spin the data off to the
2051 // transport and proceed with the next stage.
2052 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2053 + mCurrentPackage.packageName);
2054 mBackupHandler.removeMessages(MSG_TIMEOUT);
2055 clearAgentState();
2056
2057 ParcelFileDescriptor backupData = null;
2058 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002059 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002060 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002061 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002062 if (mStatus == BackupConstants.TRANSPORT_OK) {
2063 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002064 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate8e294d42011-08-31 20:37:12 -07002065 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002066 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002067
Dan Egnor83861e72009-09-17 16:17:55 -07002068 // TODO - We call finishBackup() for each application backed up, because
2069 // we need to know now whether it succeeded or failed. Instead, we should
2070 // hold off on finishBackup() until the end, which implies holding off on
2071 // renaming *all* the output state files (see below) until that happens.
2072
Christopher Tate8e294d42011-08-31 20:37:12 -07002073 if (mStatus == BackupConstants.TRANSPORT_OK) {
2074 mStatus = mTransport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07002075 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002076 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002077 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002078 }
2079
2080 // After successful transport, delete the now-stale data
2081 // and juggle the files so that next time we supply the agent
2082 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002083 if (mStatus == BackupConstants.TRANSPORT_OK) {
2084 mBackupDataName.delete();
2085 mNewStateName.renameTo(mSavedStateName);
2086 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2087 mCurrentPackage.packageName, size);
2088 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002089 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002090 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2091 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002092 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002093 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002094 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2095 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2096 mCurrentPackage.packageName);
2097 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002098 } finally {
2099 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002100 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002101
Christopher Tate8e294d42011-08-31 20:37:12 -07002102 // If we encountered an error here it's a transport-level failure. That
2103 // means we need to halt everything and reschedule everything for next time.
2104 final BackupState nextState;
2105 if (mStatus != BackupConstants.TRANSPORT_OK) {
2106 revertAndEndBackup();
2107 nextState = BackupState.FINAL;
2108 } else {
2109 // Success! Proceed with the next app if any, otherwise we're done.
2110 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2111 }
2112
2113 executeNextState(nextState);
2114 }
2115
2116 @Override
2117 public void handleTimeout() {
2118 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2119 // it for the next time we run a backup pass.
2120 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2121 // fail repeatedly (i.e. have proved themselves to be buggy).
2122 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2123 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2124 "timeout");
2125 agentErrorCleanup();
2126 dataChangedImpl(mCurrentPackage.packageName);
2127 }
2128
2129 void revertAndEndBackup() {
2130 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2131 for (BackupRequest request : mOriginalQueue) {
2132 dataChangedImpl(request.packageName);
2133 }
2134 // We also want to reset the backup schedule based on whatever
2135 // the transport suggests by way of retry/backoff time.
2136 restartBackupAlarm();
2137 }
2138
2139 void agentErrorCleanup() {
2140 mBackupDataName.delete();
2141 mNewStateName.delete();
2142 clearAgentState();
2143
2144 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2145 }
2146
2147 // Cleanup common to both success and failure cases
2148 void clearAgentState() {
2149 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2150 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2151 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2152 mSavedState = mBackupData = mNewState = null;
2153 synchronized (mCurrentOpLock) {
2154 mCurrentOperations.clear();
2155 }
2156
2157 // If this was a pseudopackage there's no associated Activity Manager state
2158 if (mCurrentPackage.applicationInfo != null) {
2159 try { // unbind even on timeout, just in case
2160 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2161 } catch (RemoteException e) {}
2162 }
2163 }
2164
2165 void restartBackupAlarm() {
2166 synchronized (mQueueLock) {
2167 try {
2168 startBackupAlarmsLocked(mTransport.requestBackupTime());
2169 } catch (RemoteException e) { /* cannot happen */ }
2170 }
2171 }
2172
2173 void executeNextState(BackupState nextState) {
2174 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2175 + this + " nextState=" + nextState);
2176 mCurrentState = nextState;
2177 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2178 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002179 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002180 }
2181
Christopher Tatedf01dea2009-06-09 20:45:02 -07002182
Christopher Tate4a627c72011-04-01 14:43:32 -07002183 // ----- Full backup to a file/socket -----
2184
2185 class PerformFullBackupTask implements Runnable {
2186 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002187 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002188 IFullBackupRestoreObserver mObserver;
2189 boolean mIncludeApks;
2190 boolean mIncludeShared;
2191 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002192 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002193 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002194 String mCurrentPassword;
2195 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002196 AtomicBoolean mLatchObject;
2197 File mFilesDir;
2198 File mManifestFile;
2199
Christopher Tate7926a692011-07-11 11:31:57 -07002200 class FullBackupRunner implements Runnable {
2201 PackageInfo mPackage;
2202 IBackupAgent mAgent;
2203 ParcelFileDescriptor mPipe;
2204 int mToken;
2205 boolean mSendApk;
2206
2207 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2208 int token, boolean sendApk) throws IOException {
2209 mPackage = pack;
2210 mAgent = agent;
2211 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2212 mToken = token;
2213 mSendApk = sendApk;
2214 }
2215
2216 @Override
2217 public void run() {
2218 try {
2219 BackupDataOutput output = new BackupDataOutput(
2220 mPipe.getFileDescriptor());
2221
Christopher Tatec58efa62011-08-01 19:20:14 -07002222 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07002223 writeAppManifest(mPackage, mManifestFile, mSendApk);
2224 FullBackup.backupToTar(mPackage.packageName, null, null,
2225 mFilesDir.getAbsolutePath(),
2226 mManifestFile.getAbsolutePath(),
2227 output);
2228
2229 if (mSendApk) {
2230 writeApkToBackup(mPackage, output);
2231 }
2232
Christopher Tatec58efa62011-08-01 19:20:14 -07002233 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002234 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002235 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2236 } catch (IOException e) {
2237 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2238 } catch (RemoteException e) {
2239 Slog.e(TAG, "Remote agent vanished during full backup of "
2240 + mPackage.packageName);
2241 } finally {
2242 try {
2243 mPipe.close();
2244 } catch (IOException e) {}
2245 }
2246 }
2247 }
2248
Christopher Tate4a627c72011-04-01 14:43:32 -07002249 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002250 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002251 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002252 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002253 mOutputFile = fd;
2254 mObserver = observer;
2255 mIncludeApks = includeApks;
2256 mIncludeShared = includeShared;
2257 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002258 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002259 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002260 mCurrentPassword = curPassword;
2261 // when backing up, if there is a current backup password, we require that
2262 // the user use a nonempty encryption password as well. if one is supplied
2263 // in the UI we use that, but if the UI was left empty we fall back to the
2264 // current backup password (which was supplied by the user as well).
2265 if (encryptPassword == null || "".equals(encryptPassword)) {
2266 mEncryptPassword = curPassword;
2267 } else {
2268 mEncryptPassword = encryptPassword;
2269 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002270 mLatchObject = latch;
2271
2272 mFilesDir = new File("/data/system");
2273 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2274 }
2275
2276 @Override
2277 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002278 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002279
Christopher Tateb0628bf2011-06-02 15:08:13 -07002280 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002281 sendStartBackup();
2282
2283 // doAllApps supersedes the package set if any
2284 if (mAllApps) {
2285 packagesToBackup = mPackageManager.getInstalledPackages(
2286 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002287 // Exclude system apps if we've been asked to do so
2288 if (mIncludeSystem == false) {
2289 for (int i = 0; i < packagesToBackup.size(); ) {
2290 PackageInfo pkg = packagesToBackup.get(i);
2291 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2292 packagesToBackup.remove(i);
2293 } else {
2294 i++;
2295 }
2296 }
2297 }
2298 }
2299
2300 // Now process the command line argument packages, if any. Note that explicitly-
2301 // named system-partition packages will be included even if includeSystem was
2302 // set to false.
2303 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002304 for (String pkgName : mPackages) {
2305 try {
2306 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2307 PackageManager.GET_SIGNATURES));
2308 } catch (NameNotFoundException e) {
2309 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2310 }
2311 }
2312 }
2313
Christopher Tatea858cb02011-06-03 12:27:51 -07002314 // Cull any packages that have indicated that backups are not permitted.
2315 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002316 PackageInfo pkg = packagesToBackup.get(i);
2317 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002318 packagesToBackup.remove(i);
2319 } else {
2320 i++;
2321 }
2322 }
2323
Christopher Tate7926a692011-07-11 11:31:57 -07002324 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002325 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002326
Christopher Tate4a627c72011-04-01 14:43:32 -07002327 PackageInfo pkg = null;
2328 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002329 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002330 boolean compressing = COMPRESS_FULL_BACKUPS;
2331 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002332
Christopher Tateeef4ae42011-08-05 13:15:53 -07002333 // Verify that the given password matches the currently-active
2334 // backup password, if any
2335 if (hasBackupPassword()) {
2336 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2337 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2338 return;
2339 }
2340 }
2341
Christopher Tate7bdb0962011-07-13 19:30:21 -07002342 // Write the global file header. All strings are UTF-8 encoded; lines end
2343 // with a '\n' byte. Actual backup data begins immediately following the
2344 // final '\n'.
2345 //
2346 // line 1: "ANDROID BACKUP"
2347 // line 2: backup file format version, currently "1"
2348 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002349 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2350 //
2351 // When line 4 is not "none", then additional header data follows:
2352 //
2353 // line 5: user password salt [hex]
2354 // line 6: master key checksum salt [hex]
2355 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2356 // line 8: IV of the user key [hex]
2357 // line 9: master key blob [hex]
2358 // IV of the master key, master key itself, master key checksum hash
2359 //
2360 // The master key checksum is the master key plus its checksum salt, run through
2361 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2362 // correct password for decrypting the archive: the master key decrypted from
2363 // the archive using the user-supplied password is also run through PBKDF2 in
2364 // this way, and if the result does not match the checksum as stored in the
2365 // archive, then we know that the user-supplied password does not match the
2366 // archive's.
2367 StringBuilder headerbuf = new StringBuilder(1024);
2368
Christopher Tate7bdb0962011-07-13 19:30:21 -07002369 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002370 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2371 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002372
2373 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002374 // Set up the encryption stage if appropriate, and emit the correct header
2375 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002376 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2377 } else {
2378 headerbuf.append("none\n");
2379 }
2380
Christopher Tate7bdb0962011-07-13 19:30:21 -07002381 byte[] header = headerbuf.toString().getBytes("UTF-8");
2382 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002383
2384 // Set up the compression stage feeding into the encryption stage (if any)
2385 if (compressing) {
2386 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2387 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2388 }
2389
2390 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002391 } catch (Exception e) {
2392 // Should never happen!
2393 Slog.e(TAG, "Unable to emit archive header", e);
2394 return;
2395 }
2396
Christopher Tateb0628bf2011-06-02 15:08:13 -07002397 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002398 int N = packagesToBackup.size();
2399 for (int i = 0; i < N; i++) {
2400 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002401 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002402 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002403
Christopher Tate6853fcf2011-08-10 17:52:21 -07002404 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002405 if (mIncludeShared) {
2406 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002407 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002408
2409 // Done!
2410 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002411 } catch (RemoteException e) {
2412 Slog.e(TAG, "App died during full backup");
2413 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002414 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002415 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002416 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002417 mOutputFile.close();
2418 } catch (IOException e) {
2419 /* nothing we can do about this */
2420 }
2421 synchronized (mCurrentOpLock) {
2422 mCurrentOperations.clear();
2423 }
2424 synchronized (mLatchObject) {
2425 mLatchObject.set(true);
2426 mLatchObject.notifyAll();
2427 }
2428 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002429 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002430 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002431 }
2432 }
2433
Christopher Tate2efd2db2011-07-19 16:32:49 -07002434 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2435 OutputStream ofstream) throws Exception {
2436 // User key will be used to encrypt the master key.
2437 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002438 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002439 PBKDF2_HASH_ROUNDS);
2440
2441 // the master key is random for each backup
2442 byte[] masterPw = new byte[256 / 8];
2443 mRng.nextBytes(masterPw);
2444 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2445
2446 // primary encryption of the datastream with the random key
2447 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2448 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2449 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2450 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2451
2452 // line 4: name of encryption algorithm
2453 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2454 headerbuf.append('\n');
2455 // line 5: user password salt [hex]
2456 headerbuf.append(byteArrayToHex(newUserSalt));
2457 headerbuf.append('\n');
2458 // line 6: master key checksum salt [hex]
2459 headerbuf.append(byteArrayToHex(checksumSalt));
2460 headerbuf.append('\n');
2461 // line 7: number of PBKDF2 rounds used [decimal]
2462 headerbuf.append(PBKDF2_HASH_ROUNDS);
2463 headerbuf.append('\n');
2464
2465 // line 8: IV of the user key [hex]
2466 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2467 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2468
2469 byte[] IV = mkC.getIV();
2470 headerbuf.append(byteArrayToHex(IV));
2471 headerbuf.append('\n');
2472
2473 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2474 // [byte] IV length = Niv
2475 // [array of Niv bytes] IV itself
2476 // [byte] master key length = Nmk
2477 // [array of Nmk bytes] master key itself
2478 // [byte] MK checksum hash length = Nck
2479 // [array of Nck bytes] master key checksum hash
2480 //
2481 // The checksum is the (master key + checksum salt), run through the
2482 // stated number of PBKDF2 rounds
2483 IV = c.getIV();
2484 byte[] mk = masterKeySpec.getEncoded();
2485 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2486 checksumSalt, PBKDF2_HASH_ROUNDS);
2487
2488 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2489 + checksum.length + 3);
2490 DataOutputStream mkOut = new DataOutputStream(blob);
2491 mkOut.writeByte(IV.length);
2492 mkOut.write(IV);
2493 mkOut.writeByte(mk.length);
2494 mkOut.write(mk);
2495 mkOut.writeByte(checksum.length);
2496 mkOut.write(checksum);
2497 mkOut.flush();
2498 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2499 headerbuf.append(byteArrayToHex(encryptedMk));
2500 headerbuf.append('\n');
2501
2502 return finalOutput;
2503 }
2504
2505 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002506 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002507 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2508
2509 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2510 IApplicationThread.BACKUP_MODE_FULL);
2511 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002512 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002513 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002514 pipes = ParcelFileDescriptor.createPipe();
2515
Christopher Tateb0628bf2011-06-02 15:08:13 -07002516 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002517 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002518 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2519 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2520 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2521
2522 sendOnBackupPackage(pkg.packageName);
2523
Christopher Tate7926a692011-07-11 11:31:57 -07002524 final int token = generateToken();
2525 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2526 token, sendApk);
2527 pipes[1].close(); // the runner has dup'd it
2528 pipes[1] = null;
2529 Thread t = new Thread(runner);
2530 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002531
Christopher Tate7926a692011-07-11 11:31:57 -07002532 // Now pull data from the app and stuff it into the compressor
2533 try {
2534 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2535 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002536
Christopher Tate7926a692011-07-11 11:31:57 -07002537 byte[] buffer = new byte[16 * 1024];
2538 int chunkTotal;
2539 while ((chunkTotal = in.readInt()) > 0) {
2540 while (chunkTotal > 0) {
2541 int toRead = (chunkTotal > buffer.length)
2542 ? buffer.length : chunkTotal;
2543 int nRead = in.read(buffer, 0, toRead);
2544 out.write(buffer, 0, nRead);
2545 chunkTotal -= nRead;
2546 }
2547 }
2548 } catch (IOException e) {
2549 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002550 }
2551
Christopher Tateb0628bf2011-06-02 15:08:13 -07002552 if (!waitUntilOperationComplete(token)) {
2553 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2554 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002555 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002556 }
Christopher Tate7926a692011-07-11 11:31:57 -07002557
Christopher Tateb0628bf2011-06-02 15:08:13 -07002558 } catch (IOException e) {
2559 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002560 } finally {
2561 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002562 // flush after every package
2563 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002564 if (pipes != null) {
2565 if (pipes[0] != null) pipes[0].close();
2566 if (pipes[1] != null) pipes[1].close();
2567 }
Christopher Tate7926a692011-07-11 11:31:57 -07002568 } catch (IOException e) {
2569 Slog.w(TAG, "Error bringing down backup stack");
2570 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002571 }
2572 } else {
2573 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2574 }
2575 tearDown(pkg);
2576 }
2577
Christopher Tate79ec80d2011-06-24 14:58:49 -07002578 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2579 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2580 final String appSourceDir = pkg.applicationInfo.sourceDir;
2581 final String apkDir = new File(appSourceDir).getParent();
2582 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2583 apkDir, appSourceDir, output);
2584
2585 // Save associated .obb content if it exists and we did save the apk
2586 // check for .obb and save those too
2587 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2588 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002589 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002590 File[] obbFiles = obbDir.listFiles();
2591 if (obbFiles != null) {
2592 final String obbDirName = obbDir.getAbsolutePath();
2593 for (File obb : obbFiles) {
2594 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2595 obbDirName, obb.getAbsolutePath(), output);
2596 }
2597 }
2598 }
2599 }
2600
Christopher Tateb0628bf2011-06-02 15:08:13 -07002601 private void backupSharedStorage() throws RemoteException {
2602 PackageInfo pkg = null;
2603 try {
2604 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2605 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2606 IApplicationThread.BACKUP_MODE_FULL);
2607 if (agent != null) {
2608 sendOnBackupPackage("Shared storage");
2609
2610 final int token = generateToken();
Christopher Tate8e294d42011-08-31 20:37:12 -07002611 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL, null);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002612 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002613 if (!waitUntilOperationComplete(token)) {
2614 Slog.e(TAG, "Full backup failed on shared storage");
2615 } else {
2616 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2617 }
2618 } else {
2619 Slog.e(TAG, "Could not bind to shared storage backup agent");
2620 }
2621 } catch (NameNotFoundException e) {
2622 Slog.e(TAG, "Shared storage backup package not found");
2623 } finally {
2624 tearDown(pkg);
2625 }
2626 }
2627
Christopher Tate6853fcf2011-08-10 17:52:21 -07002628 private void finalizeBackup(OutputStream out) {
2629 try {
2630 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2631 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2632 out.write(eof);
2633 } catch (IOException e) {
2634 Slog.w(TAG, "Error attempting to finalize backup stream");
2635 }
2636 }
2637
Christopher Tate4a627c72011-04-01 14:43:32 -07002638 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2639 throws IOException {
2640 // Manifest format. All data are strings ending in LF:
2641 // BACKUP_MANIFEST_VERSION, currently 1
2642 //
2643 // Version 1:
2644 // package name
2645 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002646 // platform versionCode
2647 // getInstallerPackageName() for this package (maybe empty)
2648 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002649 // number of signatures == N
2650 // N*: signature byte array in ascii format per Signature.toCharsString()
2651 StringBuilder builder = new StringBuilder(4096);
2652 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2653
2654 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2655 printer.println(pkg.packageName);
2656 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002657 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2658
2659 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2660 printer.println((installerName != null) ? installerName : "");
2661
Christopher Tate4a627c72011-04-01 14:43:32 -07002662 printer.println(withApk ? "1" : "0");
2663 if (pkg.signatures == null) {
2664 printer.println("0");
2665 } else {
2666 printer.println(Integer.toString(pkg.signatures.length));
2667 for (Signature sig : pkg.signatures) {
2668 printer.println(sig.toCharsString());
2669 }
2670 }
2671
2672 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002673 outstream.write(builder.toString().getBytes());
2674 outstream.close();
2675 }
2676
2677 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002678 if (pkg != null) {
2679 final ApplicationInfo app = pkg.applicationInfo;
2680 if (app != null) {
2681 try {
2682 // unbind and tidy up even on timeout or failure, just in case
2683 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002684
Christopher Tateb0628bf2011-06-02 15:08:13 -07002685 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002686 if (app.uid != Process.SYSTEM_UID
2687 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002688 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002689 mActivityManager.killApplicationProcess(app.processName, app.uid);
2690 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002691 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002692 }
2693 } catch (RemoteException e) {
2694 Slog.d(TAG, "Lost app trying to shut down");
2695 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002696 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002697 }
2698 }
2699
2700 // wrappers for observer use
2701 void sendStartBackup() {
2702 if (mObserver != null) {
2703 try {
2704 mObserver.onStartBackup();
2705 } catch (RemoteException e) {
2706 Slog.w(TAG, "full backup observer went away: startBackup");
2707 mObserver = null;
2708 }
2709 }
2710 }
2711
2712 void sendOnBackupPackage(String name) {
2713 if (mObserver != null) {
2714 try {
2715 // TODO: use a more user-friendly name string
2716 mObserver.onBackupPackage(name);
2717 } catch (RemoteException e) {
2718 Slog.w(TAG, "full backup observer went away: backupPackage");
2719 mObserver = null;
2720 }
2721 }
2722 }
2723
2724 void sendEndBackup() {
2725 if (mObserver != null) {
2726 try {
2727 mObserver.onEndBackup();
2728 } catch (RemoteException e) {
2729 Slog.w(TAG, "full backup observer went away: endBackup");
2730 mObserver = null;
2731 }
2732 }
2733 }
2734 }
2735
2736
Christopher Tate75a99702011-05-18 16:28:19 -07002737 // ----- Full restore from a file/socket -----
2738
2739 // Description of a file in the restore datastream
2740 static class FileMetadata {
2741 String packageName; // name of the owning app
2742 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002743 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002744 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2745 String path; // subpath within the semantic domain
2746 long mode; // e.g. 0666 (actually int)
2747 long mtime; // last mod time, UTC time_t (actually int)
2748 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002749
2750 @Override
2751 public String toString() {
2752 StringBuilder sb = new StringBuilder(128);
2753 sb.append("FileMetadata{");
2754 sb.append(packageName); sb.append(',');
2755 sb.append(type); sb.append(',');
2756 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2757 sb.append(size);
2758 sb.append('}');
2759 return sb.toString();
2760 }
Christopher Tate75a99702011-05-18 16:28:19 -07002761 }
2762
2763 enum RestorePolicy {
2764 IGNORE,
2765 ACCEPT,
2766 ACCEPT_IF_APK
2767 }
2768
2769 class PerformFullRestoreTask implements Runnable {
2770 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002771 String mCurrentPassword;
2772 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002773 IFullBackupRestoreObserver mObserver;
2774 AtomicBoolean mLatchObject;
2775 IBackupAgent mAgent;
2776 String mAgentPackage;
2777 ApplicationInfo mTargetApp;
2778 ParcelFileDescriptor[] mPipes = null;
2779
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002780 long mBytes;
2781
Christopher Tate75a99702011-05-18 16:28:19 -07002782 // possible handling states for a given package in the restore dataset
2783 final HashMap<String, RestorePolicy> mPackagePolicies
2784 = new HashMap<String, RestorePolicy>();
2785
2786 // installer package names for each encountered app, derived from the manifests
2787 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2788
2789 // Signatures for a given package found in its manifest file
2790 final HashMap<String, Signature[]> mManifestSignatures
2791 = new HashMap<String, Signature[]>();
2792
2793 // Packages we've already wiped data on when restoring their first file
2794 final HashSet<String> mClearedPackages = new HashSet<String>();
2795
Christopher Tate728a1c42011-07-28 18:03:03 -07002796 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002797 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002798 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002799 mCurrentPassword = curPassword;
2800 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002801 mObserver = observer;
2802 mLatchObject = latch;
2803 mAgent = null;
2804 mAgentPackage = null;
2805 mTargetApp = null;
2806
2807 // Which packages we've already wiped data on. We prepopulate this
2808 // with a whitelist of packages known to be unclearable.
2809 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002810 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002811
Christopher Tate75a99702011-05-18 16:28:19 -07002812 }
2813
2814 class RestoreFileRunnable implements Runnable {
2815 IBackupAgent mAgent;
2816 FileMetadata mInfo;
2817 ParcelFileDescriptor mSocket;
2818 int mToken;
2819
2820 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2821 ParcelFileDescriptor socket, int token) throws IOException {
2822 mAgent = agent;
2823 mInfo = info;
2824 mToken = token;
2825
2826 // This class is used strictly for process-local binder invocations. The
2827 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2828 // do not automatically get a 'dup'ed descriptor that we can can continue
2829 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2830 // before proceeding to do the restore.
2831 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2832 }
2833
2834 @Override
2835 public void run() {
2836 try {
2837 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2838 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2839 mToken, mBackupManagerBinder);
2840 } catch (RemoteException e) {
2841 // never happens; this is used strictly for local binder calls
2842 }
2843 }
2844 }
2845
2846 @Override
2847 public void run() {
2848 Slog.i(TAG, "--- Performing full-dataset restore ---");
2849 sendStartRestore();
2850
Christopher Tateb0628bf2011-06-02 15:08:13 -07002851 // Are we able to restore shared-storage data?
2852 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2853 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2854 }
2855
Christopher Tate2efd2db2011-07-19 16:32:49 -07002856 FileInputStream rawInStream = null;
2857 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002858 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002859 if (hasBackupPassword()) {
2860 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2861 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2862 return;
2863 }
2864 }
2865
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002866 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002867 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002868 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2869 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002870
2871 // First, parse out the unencrypted/uncompressed header
2872 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002873 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002874 final InputStream in;
2875
2876 boolean okay = false;
2877 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2878 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002879 rawDataIn.readFully(streamHeader);
2880 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2881 if (Arrays.equals(magicBytes, streamHeader)) {
2882 // okay, header looks good. now parse out the rest of the fields.
2883 String s = readHeaderLine(rawInStream);
2884 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2885 // okay, it's a version we recognize
2886 s = readHeaderLine(rawInStream);
2887 compressed = (Integer.parseInt(s) != 0);
2888 s = readHeaderLine(rawInStream);
2889 if (s.equals("none")) {
2890 // no more header to parse; we're good to go
2891 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002892 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002893 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2894 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002895 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002896 }
2897 } else Slog.w(TAG, "Archive is encrypted but no password given");
2898 } else Slog.w(TAG, "Wrong header version: " + s);
2899 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002900
2901 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002902 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002903 return;
2904 }
2905
2906 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002907 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002908
2909 boolean didRestore;
2910 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002911 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002912 } while (didRestore);
2913
Christopher Tatec58efa62011-08-01 19:20:14 -07002914 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002915 } catch (IOException e) {
2916 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002917 } finally {
2918 tearDownPipes();
2919 tearDownAgent(mTargetApp);
2920
2921 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002922 if (rawDataIn != null) rawDataIn.close();
2923 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002924 mInputFile.close();
2925 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002926 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002927 /* nothing we can do about this */
2928 }
2929 synchronized (mCurrentOpLock) {
2930 mCurrentOperations.clear();
2931 }
2932 synchronized (mLatchObject) {
2933 mLatchObject.set(true);
2934 mLatchObject.notifyAll();
2935 }
2936 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07002937 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002938 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07002939 }
2940 }
2941
Christopher Tate7bdb0962011-07-13 19:30:21 -07002942 String readHeaderLine(InputStream in) throws IOException {
2943 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002944 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002945 while ((c = in.read()) >= 0) {
2946 if (c == '\n') break; // consume and discard the newlines
2947 buffer.append((char)c);
2948 }
2949 return buffer.toString();
2950 }
2951
Christopher Tate2efd2db2011-07-19 16:32:49 -07002952 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2953 InputStream result = null;
2954 try {
2955 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2956
2957 String userSaltHex = readHeaderLine(rawInStream); // 5
2958 byte[] userSalt = hexToByteArray(userSaltHex);
2959
2960 String ckSaltHex = readHeaderLine(rawInStream); // 6
2961 byte[] ckSalt = hexToByteArray(ckSaltHex);
2962
2963 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2964 String userIvHex = readHeaderLine(rawInStream); // 8
2965
2966 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2967
2968 // decrypt the master key blob
2969 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002970 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002971 rounds);
2972 byte[] IV = hexToByteArray(userIvHex);
2973 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2974 c.init(Cipher.DECRYPT_MODE,
2975 new SecretKeySpec(userKey.getEncoded(), "AES"),
2976 ivSpec);
2977 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2978 byte[] mkBlob = c.doFinal(mkCipher);
2979
2980 // first, the master key IV
2981 int offset = 0;
2982 int len = mkBlob[offset++];
2983 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2984 offset += len;
2985 // then the master key itself
2986 len = mkBlob[offset++];
2987 byte[] mk = Arrays.copyOfRange(mkBlob,
2988 offset, offset + len);
2989 offset += len;
2990 // and finally the master key checksum hash
2991 len = mkBlob[offset++];
2992 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2993 offset, offset + len);
2994
2995 // now validate the decrypted master key against the checksum
2996 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2997 if (Arrays.equals(calculatedCk, mkChecksum)) {
2998 ivSpec = new IvParameterSpec(IV);
2999 c.init(Cipher.DECRYPT_MODE,
3000 new SecretKeySpec(mk, "AES"),
3001 ivSpec);
3002 // Only if all of the above worked properly will 'result' be assigned
3003 result = new CipherInputStream(rawInStream, c);
3004 } else Slog.w(TAG, "Incorrect password");
3005 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
3006 } catch (InvalidAlgorithmParameterException e) {
3007 Slog.e(TAG, "Needed parameter spec unavailable!", e);
3008 } catch (BadPaddingException e) {
3009 // This case frequently occurs when the wrong password is used to decrypt
3010 // the master key. Use the identical "incorrect password" log text as is
3011 // used in the checksum failure log in order to avoid providing additional
3012 // information to an attacker.
3013 Slog.w(TAG, "Incorrect password");
3014 } catch (IllegalBlockSizeException e) {
3015 Slog.w(TAG, "Invalid block size in master key");
3016 } catch (NoSuchAlgorithmException e) {
3017 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3018 } catch (NoSuchPaddingException e) {
3019 Slog.e(TAG, "Needed padding mechanism unavailable!");
3020 } catch (InvalidKeyException e) {
3021 Slog.w(TAG, "Illegal password; aborting");
3022 } catch (NumberFormatException e) {
3023 Slog.w(TAG, "Can't parse restore data header");
3024 } catch (IOException e) {
3025 Slog.w(TAG, "Can't read input header");
3026 }
3027
3028 return result;
3029 }
3030
Christopher Tate75a99702011-05-18 16:28:19 -07003031 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3032 FileMetadata info;
3033 try {
3034 info = readTarHeaders(instream);
3035 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003036 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003037 dumpFileMetadata(info);
3038 }
3039
3040 final String pkg = info.packageName;
3041 if (!pkg.equals(mAgentPackage)) {
3042 // okay, change in package; set up our various
3043 // bookkeeping if we haven't seen it yet
3044 if (!mPackagePolicies.containsKey(pkg)) {
3045 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3046 }
3047
3048 // Clean up the previous agent relationship if necessary,
3049 // and let the observer know we're considering a new app.
3050 if (mAgent != null) {
3051 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3052 tearDownPipes();
3053 tearDownAgent(mTargetApp);
3054 mTargetApp = null;
3055 mAgentPackage = null;
3056 }
3057 }
3058
3059 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3060 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3061 mPackageInstallers.put(pkg, info.installerPackageName);
3062 // We've read only the manifest content itself at this point,
3063 // so consume the footer before looping around to the next
3064 // input file
3065 skipTarPadding(info.size, instream);
3066 sendOnRestorePackage(pkg);
3067 } else {
3068 // Non-manifest, so it's actual file data. Is this a package
3069 // we're ignoring?
3070 boolean okay = true;
3071 RestorePolicy policy = mPackagePolicies.get(pkg);
3072 switch (policy) {
3073 case IGNORE:
3074 okay = false;
3075 break;
3076
3077 case ACCEPT_IF_APK:
3078 // If we're in accept-if-apk state, then the first file we
3079 // see MUST be the apk.
3080 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3081 if (DEBUG) Slog.d(TAG, "APK file; installing");
3082 // Try to install the app.
3083 String installerName = mPackageInstallers.get(pkg);
3084 okay = installApk(info, installerName, instream);
3085 // good to go; promote to ACCEPT
3086 mPackagePolicies.put(pkg, (okay)
3087 ? RestorePolicy.ACCEPT
3088 : RestorePolicy.IGNORE);
3089 // At this point we've consumed this file entry
3090 // ourselves, so just strip the tar footer and
3091 // go on to the next file in the input stream
3092 skipTarPadding(info.size, instream);
3093 return true;
3094 } else {
3095 // File data before (or without) the apk. We can't
3096 // handle it coherently in this case so ignore it.
3097 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3098 okay = false;
3099 }
3100 break;
3101
3102 case ACCEPT:
3103 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3104 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3105 // we can take the data without the apk, so we
3106 // *want* to do so. skip the apk by declaring this
3107 // one file not-okay without changing the restore
3108 // policy for the package.
3109 okay = false;
3110 }
3111 break;
3112
3113 default:
3114 // Something has gone dreadfully wrong when determining
3115 // the restore policy from the manifest. Ignore the
3116 // rest of this package's data.
3117 Slog.e(TAG, "Invalid policy from manifest");
3118 okay = false;
3119 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3120 break;
3121 }
3122
3123 // If the policy is satisfied, go ahead and set up to pipe the
3124 // data to the agent.
3125 if (DEBUG && okay && mAgent != null) {
3126 Slog.i(TAG, "Reusing existing agent instance");
3127 }
3128 if (okay && mAgent == null) {
3129 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3130
3131 try {
3132 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3133
3134 // If we haven't sent any data to this app yet, we probably
3135 // need to clear it first. Check that.
3136 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003137 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003138 // responsible for coherently managing a full
3139 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003140 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003141 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3142 clearApplicationDataSynchronous(pkg);
3143 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003144 if (DEBUG) Slog.d(TAG, "backup agent ("
3145 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003146 }
3147 mClearedPackages.add(pkg);
3148 } else {
3149 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3150 }
3151
3152 // All set; now set up the IPC and launch the agent
3153 setUpPipes();
3154 mAgent = bindToAgentSynchronous(mTargetApp,
3155 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3156 mAgentPackage = pkg;
3157 } catch (IOException e) {
3158 // fall through to error handling
3159 } catch (NameNotFoundException e) {
3160 // fall through to error handling
3161 }
3162
3163 if (mAgent == null) {
3164 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3165 okay = false;
3166 tearDownPipes();
3167 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3168 }
3169 }
3170
3171 // Sanity check: make sure we never give data to the wrong app. This
3172 // should never happen but a little paranoia here won't go amiss.
3173 if (okay && !pkg.equals(mAgentPackage)) {
3174 Slog.e(TAG, "Restoring data for " + pkg
3175 + " but agent is for " + mAgentPackage);
3176 okay = false;
3177 }
3178
3179 // At this point we have an agent ready to handle the full
3180 // restore data as well as a pipe for sending data to
3181 // that agent. Tell the agent to start reading from the
3182 // pipe.
3183 if (okay) {
3184 boolean agentSuccess = true;
3185 long toCopy = info.size;
3186 final int token = generateToken();
3187 try {
3188 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3189 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003190 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003191 // fire up the app's agent listening on the socket. If
3192 // the agent is running in the system process we can't
3193 // just invoke it asynchronously, so we provide a thread
3194 // for it here.
3195 if (mTargetApp.processName.equals("system")) {
3196 Slog.d(TAG, "system process agent - spinning a thread");
3197 RestoreFileRunnable runner = new RestoreFileRunnable(
3198 mAgent, info, mPipes[0], token);
3199 new Thread(runner).start();
3200 } else {
3201 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3202 info.domain, info.path, info.mode, info.mtime,
3203 token, mBackupManagerBinder);
3204 }
3205 } catch (IOException e) {
3206 // couldn't dup the socket for a process-local restore
3207 Slog.d(TAG, "Couldn't establish restore");
3208 agentSuccess = false;
3209 okay = false;
3210 } catch (RemoteException e) {
3211 // whoops, remote agent went away. We'll eat the content
3212 // ourselves, then, and not copy it over.
3213 Slog.e(TAG, "Agent crashed during full restore");
3214 agentSuccess = false;
3215 okay = false;
3216 }
3217
3218 // Copy over the data if the agent is still good
3219 if (okay) {
3220 boolean pipeOkay = true;
3221 FileOutputStream pipe = new FileOutputStream(
3222 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003223 while (toCopy > 0) {
3224 int toRead = (toCopy > buffer.length)
3225 ? buffer.length : (int)toCopy;
3226 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003227 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003228 if (nRead <= 0) break;
3229 toCopy -= nRead;
3230
3231 // send it to the output pipe as long as things
3232 // are still good
3233 if (pipeOkay) {
3234 try {
3235 pipe.write(buffer, 0, nRead);
3236 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003237 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003238 pipeOkay = false;
3239 }
3240 }
3241 }
3242
3243 // done sending that file! Now we just need to consume
3244 // the delta from info.size to the end of block.
3245 skipTarPadding(info.size, instream);
3246
3247 // and now that we've sent it all, wait for the remote
3248 // side to acknowledge receipt
3249 agentSuccess = waitUntilOperationComplete(token);
3250 }
3251
3252 // okay, if the remote end failed at any point, deal with
3253 // it by ignoring the rest of the restore on it
3254 if (!agentSuccess) {
3255 mBackupHandler.removeMessages(MSG_TIMEOUT);
3256 tearDownPipes();
3257 tearDownAgent(mTargetApp);
3258 mAgent = null;
3259 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3260 }
3261 }
3262
3263 // Problems setting up the agent communication, or an already-
3264 // ignored package: skip to the next tar stream entry by
3265 // reading and discarding this file.
3266 if (!okay) {
3267 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3268 long bytesToConsume = (info.size + 511) & ~511;
3269 while (bytesToConsume > 0) {
3270 int toRead = (bytesToConsume > buffer.length)
3271 ? buffer.length : (int)bytesToConsume;
3272 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003273 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003274 if (nRead <= 0) break;
3275 bytesToConsume -= nRead;
3276 }
3277 }
3278 }
3279 }
3280 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003281 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003282 // treat as EOF
3283 info = null;
3284 }
3285
3286 return (info != null);
3287 }
3288
3289 void setUpPipes() throws IOException {
3290 mPipes = ParcelFileDescriptor.createPipe();
3291 }
3292
3293 void tearDownPipes() {
3294 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003295 try {
3296 mPipes[0].close();
3297 mPipes[0] = null;
3298 mPipes[1].close();
3299 mPipes[1] = null;
3300 } catch (IOException e) {
3301 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003302 }
3303 mPipes = null;
3304 }
3305 }
3306
3307 void tearDownAgent(ApplicationInfo app) {
3308 if (mAgent != null) {
3309 try {
3310 // unbind and tidy up even on timeout or failure, just in case
3311 mActivityManager.unbindBackupAgent(app);
3312
3313 // The agent was running with a stub Application object, so shut it down.
3314 // !!! We hardcode the confirmation UI's package name here rather than use a
3315 // manifest flag! TODO something less direct.
3316 if (app.uid != Process.SYSTEM_UID
3317 && !app.packageName.equals("com.android.backupconfirm")) {
3318 if (DEBUG) Slog.d(TAG, "Killing host process");
3319 mActivityManager.killApplicationProcess(app.processName, app.uid);
3320 } else {
3321 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3322 }
3323 } catch (RemoteException e) {
3324 Slog.d(TAG, "Lost app trying to shut down");
3325 }
3326 mAgent = null;
3327 }
3328 }
3329
3330 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3331 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003332 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003333 int mResult;
3334
3335 public void reset() {
3336 synchronized (mDone) {
3337 mDone.set(false);
3338 }
3339 }
3340
3341 public void waitForCompletion() {
3342 synchronized (mDone) {
3343 while (mDone.get() == false) {
3344 try {
3345 mDone.wait();
3346 } catch (InterruptedException e) { }
3347 }
3348 }
3349 }
3350
3351 int getResult() {
3352 return mResult;
3353 }
3354
3355 @Override
3356 public void packageInstalled(String packageName, int returnCode)
3357 throws RemoteException {
3358 synchronized (mDone) {
3359 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003360 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003361 mDone.set(true);
3362 mDone.notifyAll();
3363 }
3364 }
3365 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003366
3367 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3368 final AtomicBoolean mDone = new AtomicBoolean();
3369 int mResult;
3370
3371 public void reset() {
3372 synchronized (mDone) {
3373 mDone.set(false);
3374 }
3375 }
3376
3377 public void waitForCompletion() {
3378 synchronized (mDone) {
3379 while (mDone.get() == false) {
3380 try {
3381 mDone.wait();
3382 } catch (InterruptedException e) { }
3383 }
3384 }
3385 }
3386
3387 @Override
3388 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3389 synchronized (mDone) {
3390 mResult = returnCode;
3391 mDone.set(true);
3392 mDone.notifyAll();
3393 }
3394 }
3395 }
3396
Christopher Tate75a99702011-05-18 16:28:19 -07003397 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003398 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003399
3400 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3401 boolean okay = true;
3402
3403 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3404
3405 // The file content is an .apk file. Copy it out to a staging location and
3406 // attempt to install it.
3407 File apkFile = new File(mDataDir, info.packageName);
3408 try {
3409 FileOutputStream apkStream = new FileOutputStream(apkFile);
3410 byte[] buffer = new byte[32 * 1024];
3411 long size = info.size;
3412 while (size > 0) {
3413 long toRead = (buffer.length < size) ? buffer.length : size;
3414 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003415 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003416 apkStream.write(buffer, 0, didRead);
3417 size -= didRead;
3418 }
3419 apkStream.close();
3420
3421 // make sure the installer can read it
3422 apkFile.setReadable(true, false);
3423
3424 // Now install it
3425 Uri packageUri = Uri.fromFile(apkFile);
3426 mInstallObserver.reset();
3427 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003428 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3429 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003430 mInstallObserver.waitForCompletion();
3431
3432 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3433 // The only time we continue to accept install of data even if the
3434 // apk install failed is if we had already determined that we could
3435 // accept the data regardless.
3436 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3437 okay = false;
3438 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003439 } else {
3440 // Okay, the install succeeded. Make sure it was the right app.
3441 boolean uninstall = false;
3442 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3443 Slog.w(TAG, "Restore stream claimed to include apk for "
3444 + info.packageName + " but apk was really "
3445 + mInstallObserver.mPackageName);
3446 // delete the package we just put in place; it might be fraudulent
3447 okay = false;
3448 uninstall = true;
3449 } else {
3450 try {
3451 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3452 PackageManager.GET_SIGNATURES);
3453 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3454 Slog.w(TAG, "Restore stream contains apk of package "
3455 + info.packageName + " but it disallows backup/restore");
3456 okay = false;
3457 } else {
3458 // So far so good -- do the signatures match the manifest?
3459 Signature[] sigs = mManifestSignatures.get(info.packageName);
3460 if (!signaturesMatch(sigs, pkg)) {
3461 Slog.w(TAG, "Installed app " + info.packageName
3462 + " signatures do not match restore manifest");
3463 okay = false;
3464 uninstall = true;
3465 }
3466 }
3467 } catch (NameNotFoundException e) {
3468 Slog.w(TAG, "Install of package " + info.packageName
3469 + " succeeded but now not found");
3470 okay = false;
3471 }
3472 }
3473
3474 // If we're not okay at this point, we need to delete the package
3475 // that we just installed.
3476 if (uninstall) {
3477 mDeleteObserver.reset();
3478 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3479 mDeleteObserver, 0);
3480 mDeleteObserver.waitForCompletion();
3481 }
Christopher Tate75a99702011-05-18 16:28:19 -07003482 }
3483 } catch (IOException e) {
3484 Slog.e(TAG, "Unable to transcribe restored apk for install");
3485 okay = false;
3486 } finally {
3487 apkFile.delete();
3488 }
3489
3490 return okay;
3491 }
3492
3493 // Given an actual file content size, consume the post-content padding mandated
3494 // by the tar format.
3495 void skipTarPadding(long size, InputStream instream) throws IOException {
3496 long partial = (size + 512) % 512;
3497 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003498 final int needed = 512 - (int)partial;
3499 byte[] buffer = new byte[needed];
3500 if (readExactly(instream, buffer, 0, needed) == needed) {
3501 mBytes += needed;
3502 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003503 }
3504 }
3505
3506 // Returns a policy constant; takes a buffer arg to reduce memory churn
3507 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3508 throws IOException {
3509 // Fail on suspiciously large manifest files
3510 if (info.size > 64 * 1024) {
3511 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3512 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003513
Christopher Tate75a99702011-05-18 16:28:19 -07003514 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003515 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3516 mBytes += info.size;
3517 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003518
3519 RestorePolicy policy = RestorePolicy.IGNORE;
3520 String[] str = new String[1];
3521 int offset = 0;
3522
3523 try {
3524 offset = extractLine(buffer, offset, str);
3525 int version = Integer.parseInt(str[0]);
3526 if (version == BACKUP_MANIFEST_VERSION) {
3527 offset = extractLine(buffer, offset, str);
3528 String manifestPackage = str[0];
3529 // TODO: handle <original-package>
3530 if (manifestPackage.equals(info.packageName)) {
3531 offset = extractLine(buffer, offset, str);
3532 version = Integer.parseInt(str[0]); // app version
3533 offset = extractLine(buffer, offset, str);
3534 int platformVersion = Integer.parseInt(str[0]);
3535 offset = extractLine(buffer, offset, str);
3536 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3537 offset = extractLine(buffer, offset, str);
3538 boolean hasApk = str[0].equals("1");
3539 offset = extractLine(buffer, offset, str);
3540 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003541 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003542 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003543 for (int i = 0; i < numSigs; i++) {
3544 offset = extractLine(buffer, offset, str);
3545 sigs[i] = new Signature(str[0]);
3546 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003547 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003548
3549 // Okay, got the manifest info we need...
3550 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003551 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3552 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003553 // Fall through to IGNORE if the app explicitly disallows backup
3554 final int flags = pkgInfo.applicationInfo.flags;
3555 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3556 // Verify signatures against any installed version; if they
3557 // don't match, then we fall though and ignore the data. The
3558 // signatureMatch() method explicitly ignores the signature
3559 // check for packages installed on the system partition, because
3560 // such packages are signed with the platform cert instead of
3561 // the app developer's cert, so they're different on every
3562 // device.
3563 if (signaturesMatch(sigs, pkgInfo)) {
3564 if (pkgInfo.versionCode >= version) {
3565 Slog.i(TAG, "Sig + version match; taking data");
3566 policy = RestorePolicy.ACCEPT;
3567 } else {
3568 // The data is from a newer version of the app than
3569 // is presently installed. That means we can only
3570 // use it if the matching apk is also supplied.
3571 Slog.d(TAG, "Data version " + version
3572 + " is newer than installed version "
3573 + pkgInfo.versionCode + " - requiring apk");
3574 policy = RestorePolicy.ACCEPT_IF_APK;
3575 }
Christopher Tate75a99702011-05-18 16:28:19 -07003576 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003577 Slog.w(TAG, "Restore manifest signatures do not match "
3578 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003579 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003580 } else {
3581 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3582 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003583 }
3584 } catch (NameNotFoundException e) {
3585 // Okay, the target app isn't installed. We can process
3586 // the restore properly only if the dataset provides the
3587 // apk file and we can successfully install it.
3588 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3589 + " not installed; requiring apk in dataset");
3590 policy = RestorePolicy.ACCEPT_IF_APK;
3591 }
3592
3593 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3594 Slog.i(TAG, "Cannot restore package " + info.packageName
3595 + " without the matching .apk");
3596 }
3597 } else {
3598 Slog.i(TAG, "Missing signature on backed-up package "
3599 + info.packageName);
3600 }
3601 } else {
3602 Slog.i(TAG, "Expected package " + info.packageName
3603 + " but restore manifest claims " + manifestPackage);
3604 }
3605 } else {
3606 Slog.i(TAG, "Unknown restore manifest version " + version
3607 + " for package " + info.packageName);
3608 }
3609 } catch (NumberFormatException e) {
3610 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003611 } catch (IllegalArgumentException e) {
3612 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003613 }
3614
3615 return policy;
3616 }
3617
3618 // Builds a line from a byte buffer starting at 'offset', and returns
3619 // the index of the next unconsumed data in the buffer.
3620 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3621 final int end = buffer.length;
3622 if (offset >= end) throw new IOException("Incomplete data");
3623
3624 int pos;
3625 for (pos = offset; pos < end; pos++) {
3626 byte c = buffer[pos];
3627 // at LF we declare end of line, and return the next char as the
3628 // starting point for the next time through
3629 if (c == '\n') {
3630 break;
3631 }
3632 }
3633 outStr[0] = new String(buffer, offset, pos - offset);
3634 pos++; // may be pointing an extra byte past the end but that's okay
3635 return pos;
3636 }
3637
3638 void dumpFileMetadata(FileMetadata info) {
3639 if (DEBUG) {
3640 StringBuilder b = new StringBuilder(128);
3641
3642 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003643 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003644 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3645 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3646 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3647 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3648 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3649 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3650 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3651 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3652 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3653 b.append(String.format(" %9d ", info.size));
3654
3655 Date stamp = new Date(info.mtime);
3656 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3657
3658 b.append(info.packageName);
3659 b.append(" :: ");
3660 b.append(info.domain);
3661 b.append(" :: ");
3662 b.append(info.path);
3663
3664 Slog.i(TAG, b.toString());
3665 }
3666 }
3667 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3668 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3669 byte[] block = new byte[512];
3670 FileMetadata info = null;
3671
3672 boolean gotHeader = readTarHeader(instream, block);
3673 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003674 try {
3675 // okay, presume we're okay, and extract the various metadata
3676 info = new FileMetadata();
3677 info.size = extractRadix(block, 124, 12, 8);
3678 info.mtime = extractRadix(block, 136, 12, 8);
3679 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003680
Christopher Tate2efd2db2011-07-19 16:32:49 -07003681 info.path = extractString(block, 345, 155); // prefix
3682 String path = extractString(block, 0, 100);
3683 if (path.length() > 0) {
3684 if (info.path.length() > 0) info.path += '/';
3685 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003686 }
Christopher Tate75a99702011-05-18 16:28:19 -07003687
Christopher Tate2efd2db2011-07-19 16:32:49 -07003688 // tar link indicator field: 1 byte at offset 156 in the header.
3689 int typeChar = block[156];
3690 if (typeChar == 'x') {
3691 // pax extended header, so we need to read that
3692 gotHeader = readPaxExtendedHeader(instream, info);
3693 if (gotHeader) {
3694 // and after a pax extended header comes another real header -- read
3695 // that to find the real file type
3696 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003697 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003698 if (!gotHeader) throw new IOException("Bad or missing pax header");
3699
3700 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003701 }
Christopher Tate75a99702011-05-18 16:28:19 -07003702
Christopher Tate2efd2db2011-07-19 16:32:49 -07003703 switch (typeChar) {
3704 case '0': info.type = BackupAgent.TYPE_FILE; break;
3705 case '5': {
3706 info.type = BackupAgent.TYPE_DIRECTORY;
3707 if (info.size != 0) {
3708 Slog.w(TAG, "Directory entry with nonzero size in header");
3709 info.size = 0;
3710 }
3711 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003712 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003713 case 0: {
3714 // presume EOF
3715 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3716 return null;
3717 }
3718 default: {
3719 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3720 throw new IOException("Unknown entity type " + typeChar);
3721 }
Christopher Tate75a99702011-05-18 16:28:19 -07003722 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003723
3724 // Parse out the path
3725 //
3726 // first: apps/shared/unrecognized
3727 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3728 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3729 // File in shared storage. !!! TODO: implement this.
3730 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3731 info.packageName = "com.android.sharedstoragebackup";
3732 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3733 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3734 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3735 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3736 // App content! Parse out the package name and domain
3737
3738 // strip the apps/ prefix
3739 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3740
3741 // extract the package name
3742 int slash = info.path.indexOf('/');
3743 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3744 info.packageName = info.path.substring(0, slash);
3745 info.path = info.path.substring(slash+1);
3746
3747 // if it's a manifest we're done, otherwise parse out the domains
3748 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3749 slash = info.path.indexOf('/');
3750 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3751 info.domain = info.path.substring(0, slash);
3752 // validate that it's one of the domains we understand
3753 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3754 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3755 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3756 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3757 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3758 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3759 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3760 throw new IOException("Unrecognized domain " + info.domain);
3761 }
3762
3763 info.path = info.path.substring(slash + 1);
3764 }
3765 }
3766 } catch (IOException e) {
3767 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003768 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003769 HEXLOG(block);
3770 }
3771 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003772 }
3773 }
3774 return info;
3775 }
3776
Christopher Tate2efd2db2011-07-19 16:32:49 -07003777 private void HEXLOG(byte[] block) {
3778 int offset = 0;
3779 int todo = block.length;
3780 StringBuilder buf = new StringBuilder(64);
3781 while (todo > 0) {
3782 buf.append(String.format("%04x ", offset));
3783 int numThisLine = (todo > 16) ? 16 : todo;
3784 for (int i = 0; i < numThisLine; i++) {
3785 buf.append(String.format("%02x ", block[offset+i]));
3786 }
3787 Slog.i("hexdump", buf.toString());
3788 buf.setLength(0);
3789 todo -= numThisLine;
3790 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003791 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003792 }
3793
Christopher Tate6853fcf2011-08-10 17:52:21 -07003794 // Read exactly the given number of bytes into a buffer at the stated offset.
3795 // Returns false if EOF is encountered before the requested number of bytes
3796 // could be read.
3797 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3798 throws IOException {
3799 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3800
3801 int soFar = 0;
3802 while (soFar < size) {
3803 int nRead = in.read(buffer, offset + soFar, size - soFar);
3804 if (nRead <= 0) {
3805 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3806 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003807 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003808 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003809 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003810 return soFar;
3811 }
3812
3813 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3814 final int got = readExactly(instream, block, 0, 512);
3815 if (got == 0) return false; // Clean EOF
3816 if (got < 512) throw new IOException("Unable to read full block header");
3817 mBytes += 512;
3818 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003819 }
3820
3821 // overwrites 'info' fields based on the pax extended header
3822 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3823 throws IOException {
3824 // We should never see a pax extended header larger than this
3825 if (info.size > 32*1024) {
3826 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3827 + " - aborting");
3828 throw new IOException("Sanity failure: pax header size " + info.size);
3829 }
3830
3831 // read whole blocks, not just the content size
3832 int numBlocks = (int)((info.size + 511) >> 9);
3833 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003834 if (readExactly(instream, data, 0, data.length) < data.length) {
3835 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003836 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003837 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003838
3839 final int contentSize = (int) info.size;
3840 int offset = 0;
3841 do {
3842 // extract the line at 'offset'
3843 int eol = offset+1;
3844 while (eol < contentSize && data[eol] != ' ') eol++;
3845 if (eol >= contentSize) {
3846 // error: we just hit EOD looking for the end of the size field
3847 throw new IOException("Invalid pax data");
3848 }
3849 // eol points to the space between the count and the key
3850 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3851 int key = eol + 1; // start of key=value
3852 eol = offset + linelen - 1; // trailing LF
3853 int value;
3854 for (value = key+1; data[value] != '=' && value <= eol; value++);
3855 if (value > eol) {
3856 throw new IOException("Invalid pax declaration");
3857 }
3858
3859 // pax requires that key/value strings be in UTF-8
3860 String keyStr = new String(data, key, value-key, "UTF-8");
3861 // -1 to strip the trailing LF
3862 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3863
3864 if ("path".equals(keyStr)) {
3865 info.path = valStr;
3866 } else if ("size".equals(keyStr)) {
3867 info.size = Long.parseLong(valStr);
3868 } else {
3869 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3870 }
3871
3872 offset += linelen;
3873 } while (offset < contentSize);
3874
3875 return true;
3876 }
3877
3878 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3879 throws IOException {
3880 long value = 0;
3881 final int end = offset + maxChars;
3882 for (int i = offset; i < end; i++) {
3883 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003884 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003885 if (b == 0 || b == ' ') break;
3886 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003887 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003888 }
3889 value = radix * value + (b - '0');
3890 }
3891 return value;
3892 }
3893
3894 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3895 final int end = offset + maxChars;
3896 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003897 // tar string fields terminate early with a NUL
3898 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003899 return new String(data, offset, eos-offset, "US-ASCII");
3900 }
3901
3902 void sendStartRestore() {
3903 if (mObserver != null) {
3904 try {
3905 mObserver.onStartRestore();
3906 } catch (RemoteException e) {
3907 Slog.w(TAG, "full restore observer went away: startRestore");
3908 mObserver = null;
3909 }
3910 }
3911 }
3912
3913 void sendOnRestorePackage(String name) {
3914 if (mObserver != null) {
3915 try {
3916 // TODO: use a more user-friendly name string
3917 mObserver.onRestorePackage(name);
3918 } catch (RemoteException e) {
3919 Slog.w(TAG, "full restore observer went away: restorePackage");
3920 mObserver = null;
3921 }
3922 }
3923 }
3924
3925 void sendEndRestore() {
3926 if (mObserver != null) {
3927 try {
3928 mObserver.onEndRestore();
3929 } catch (RemoteException e) {
3930 Slog.w(TAG, "full restore observer went away: endRestore");
3931 mObserver = null;
3932 }
3933 }
3934 }
3935 }
3936
Christopher Tatedf01dea2009-06-09 20:45:02 -07003937 // ----- Restore handling -----
3938
Christopher Tate78dd4a72009-11-04 11:49:08 -08003939 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3940 // If the target resides on the system partition, we allow it to restore
3941 // data from the like-named package in a restore set even if the signatures
3942 // do not match. (Unlike general applications, those flashed to the system
3943 // partition will be signed with the device's platform certificate, so on
3944 // different phones the same system app will have different signatures.)
3945 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003946 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003947 return true;
3948 }
3949
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003950 // Allow unsigned apps, but not signed on one device and unsigned on the other
3951 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003952 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003953 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003954 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003955 if ((storedSigs == null || storedSigs.length == 0)
3956 && (deviceSigs == null || deviceSigs.length == 0)) {
3957 return true;
3958 }
3959 if (storedSigs == null || deviceSigs == null) {
3960 return false;
3961 }
3962
Christopher Tateabce4e82009-06-18 18:35:32 -07003963 // !!! TODO: this demands that every stored signature match one
3964 // that is present on device, and does not demand the converse.
3965 // Is this this right policy?
3966 int nStored = storedSigs.length;
3967 int nDevice = deviceSigs.length;
3968
3969 for (int i=0; i < nStored; i++) {
3970 boolean match = false;
3971 for (int j=0; j < nDevice; j++) {
3972 if (storedSigs[i].equals(deviceSigs[j])) {
3973 match = true;
3974 break;
3975 }
3976 }
3977 if (!match) {
3978 return false;
3979 }
3980 }
3981 return true;
3982 }
3983
Christopher Tate2982d062011-09-06 20:35:24 -07003984 enum RestoreState {
3985 INITIAL,
3986 DOWNLOAD_DATA,
3987 PM_METADATA,
3988 RUNNING_QUEUE,
3989 FINAL
3990 }
3991
3992 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003993 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003994 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003995 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003996 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003997 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003998 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003999 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07004000 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07004001 private long mStartRealtime;
4002 private PackageManagerBackupAgent mPmAgent;
4003 private List<PackageInfo> mAgentPackages;
4004 private ArrayList<PackageInfo> mRestorePackages;
4005 private RestoreState mCurrentState;
4006 private int mCount;
4007 private boolean mFinished;
4008 private int mStatus;
4009 private File mBackupDataName;
4010 private File mNewStateName;
4011 private File mSavedStateName;
4012 private ParcelFileDescriptor mBackupData;
4013 private ParcelFileDescriptor mNewState;
4014 private PackageInfo mCurrentPackage;
4015
Christopher Tatedf01dea2009-06-09 20:45:02 -07004016
Christopher Tate5cbbf562009-06-22 16:44:51 -07004017 class RestoreRequest {
4018 public PackageInfo app;
4019 public int storedAppVersion;
4020
4021 RestoreRequest(PackageInfo _app, int _version) {
4022 app = _app;
4023 storedAppVersion = _version;
4024 }
4025 }
4026
Christopher Tate44a27902010-01-27 17:15:49 -08004027 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004028 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004029 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004030 mCurrentState = RestoreState.INITIAL;
4031 mFinished = false;
4032 mPmAgent = null;
4033
Christopher Tatedf01dea2009-06-09 20:45:02 -07004034 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004035 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004036 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004037 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004038 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004039 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004040
Christopher Tate284f1bb2011-07-07 14:31:18 -07004041 if (filterSet != null) {
4042 mFilterSet = new HashSet<String>();
4043 for (String pkg : filterSet) {
4044 mFilterSet.add(pkg);
4045 }
4046 } else {
4047 mFilterSet = null;
4048 }
4049
Christopher Tate5cb400b2009-06-25 16:03:14 -07004050 try {
4051 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4052 } catch (RemoteException e) {
4053 // can't happen; the transport is local
4054 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004055 }
4056
Christopher Tate2982d062011-09-06 20:35:24 -07004057 // Execute one tick of whatever state machine the task implements
4058 @Override
4059 public void execute() {
4060 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4061 switch (mCurrentState) {
4062 case INITIAL:
4063 beginRestore();
4064 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004065
Christopher Tate2982d062011-09-06 20:35:24 -07004066 case DOWNLOAD_DATA:
4067 downloadRestoreData();
4068 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004069
Christopher Tate2982d062011-09-06 20:35:24 -07004070 case PM_METADATA:
4071 restorePmMetadata();
4072 break;
4073
4074 case RUNNING_QUEUE:
4075 restoreNextAgent();
4076 break;
4077
4078 case FINAL:
4079 if (!mFinished) finalizeRestore();
4080 else {
4081 Slog.e(TAG, "Duplicate finish");
4082 }
4083 mFinished = true;
4084 break;
4085 }
4086 }
4087
4088 // Initialize and set up for the PM metadata restore, which comes first
4089 void beginRestore() {
4090 // Don't account time doing the restore as inactivity of the app
4091 // that has opened a restore session.
4092 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4093
4094 // Assume error until we successfully init everything
4095 mStatus = BackupConstants.TRANSPORT_ERROR;
4096
Christopher Tatedf01dea2009-06-09 20:45:02 -07004097 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004098 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004099 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004100
Dan Egnorefe52642009-06-24 00:16:33 -07004101 // Get the list of all packages which have backup enabled.
4102 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004103 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004104 PackageInfo omPackage = new PackageInfo();
4105 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004106 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004107
Christopher Tate2982d062011-09-06 20:35:24 -07004108 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004109 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004110 // if there's a filter set, strip out anything that isn't
4111 // present before proceeding
4112 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004113 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4114 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004115 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004116 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004117 }
4118 }
Christopher Tate2982d062011-09-06 20:35:24 -07004119 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004120 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004121 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004122 Slog.i(TAG, " " + p);
4123 }
4124 }
4125 }
Christopher Tate2982d062011-09-06 20:35:24 -07004126 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004127 } else {
4128 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004129 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004130 }
Dan Egnorefe52642009-06-24 00:16:33 -07004131
Christopher Tate7d562ec2009-06-25 18:03:43 -07004132 // let the observer know that we're running
4133 if (mObserver != null) {
4134 try {
4135 // !!! TODO: get an actual count from the transport after
4136 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004137 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004138 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004139 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004140 mObserver = null;
4141 }
4142 }
Christopher Tate2982d062011-09-06 20:35:24 -07004143 } catch (RemoteException e) {
4144 // Something has gone catastrophically wrong with the transport
4145 Slog.e(TAG, "Error communicating with transport for restore");
4146 executeNextState(RestoreState.FINAL);
4147 return;
4148 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004149
Christopher Tate2982d062011-09-06 20:35:24 -07004150 mStatus = BackupConstants.TRANSPORT_OK;
4151 executeNextState(RestoreState.DOWNLOAD_DATA);
4152 }
4153
4154 void downloadRestoreData() {
4155 // Note that the download phase can be very time consuming, but we're executing
4156 // it inline here on the looper. This is "okay" because it is not calling out to
4157 // third party code; the transport is "trusted," and so we assume it is being a
4158 // good citizen and timing out etc when appropriate.
4159 //
4160 // TODO: when appropriate, move the download off the looper and rearrange the
4161 // error handling around that.
4162 try {
4163 mStatus = mTransport.startRestore(mToken,
4164 mRestorePackages.toArray(new PackageInfo[0]));
4165 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004166 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004167 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004168 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004169 return;
4170 }
Christopher Tate2982d062011-09-06 20:35:24 -07004171 } catch (RemoteException e) {
4172 Slog.e(TAG, "Error communicating with transport for restore");
4173 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4174 mStatus = BackupConstants.TRANSPORT_ERROR;
4175 executeNextState(RestoreState.FINAL);
4176 return;
4177 }
Dan Egnorefe52642009-06-24 00:16:33 -07004178
Christopher Tate2982d062011-09-06 20:35:24 -07004179 // Successful download of the data to be parceled out to the apps, so off we go.
4180 executeNextState(RestoreState.PM_METADATA);
4181 }
4182
4183 void restorePmMetadata() {
4184 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004185 String packageName = mTransport.nextRestorePackage();
4186 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004187 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004188 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004189 mStatus = BackupConstants.TRANSPORT_ERROR;
4190 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004191 return;
4192 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004193 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004194 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004195 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004196 mStatus = BackupConstants.TRANSPORT_OK;
4197 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004198 return;
4199 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004200 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004201 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004202 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004203 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004204 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004205 return;
4206 }
4207
4208 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004209 PackageInfo omPackage = new PackageInfo();
4210 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4211 mPmAgent = new PackageManagerBackupAgent(
4212 mPackageManager, mAgentPackages);
4213 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004214 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004215 // The PM agent called operationComplete() already, because our invocation
4216 // of it is process-local and therefore synchronous. That means that a
4217 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4218 // proceed with running the queue do we remove that pending message and
4219 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004220
Christopher Tate8c032472009-07-02 14:28:47 -07004221 // Verify that the backup set includes metadata. If not, we can't do
4222 // signature/version verification etc, so we simply do not proceed with
4223 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004224 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004225 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004226 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004227 "Package manager restore metadata missing");
4228 mStatus = BackupConstants.TRANSPORT_ERROR;
4229 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4230 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004231 return;
4232 }
Christopher Tate2982d062011-09-06 20:35:24 -07004233 } catch (RemoteException e) {
4234 Slog.e(TAG, "Error communicating with transport for restore");
4235 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4236 mStatus = BackupConstants.TRANSPORT_ERROR;
4237 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4238 executeNextState(RestoreState.FINAL);
4239 return;
4240 }
Christopher Tate8c032472009-07-02 14:28:47 -07004241
Christopher Tate2982d062011-09-06 20:35:24 -07004242 // Metadata is intact, so we can now run the restore queue. If we get here,
4243 // we have already enqueued the necessary next-step message on the looper.
4244 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004245
Christopher Tate2982d062011-09-06 20:35:24 -07004246 void restoreNextAgent() {
4247 try {
4248 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004249
Christopher Tate2982d062011-09-06 20:35:24 -07004250 if (packageName == null) {
4251 Slog.e(TAG, "Error getting next restore package");
4252 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4253 executeNextState(RestoreState.FINAL);
4254 return;
4255 } else if (packageName.equals("")) {
4256 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4257 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4258 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4259 executeNextState(RestoreState.FINAL);
4260 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004261 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004262
4263 if (mObserver != null) {
4264 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004265 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004266 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004267 Slog.d(TAG, "Restore observer died in onUpdate");
4268 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004269 }
4270 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004271
Christopher Tate2982d062011-09-06 20:35:24 -07004272 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4273 if (metaInfo == null) {
4274 Slog.e(TAG, "Missing metadata for " + packageName);
4275 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4276 "Package metadata missing");
4277 executeNextState(RestoreState.RUNNING_QUEUE);
4278 return;
Christopher Tate84725812010-02-04 15:52:40 -08004279 }
4280
Christopher Tate2982d062011-09-06 20:35:24 -07004281 PackageInfo packageInfo;
4282 try {
4283 int flags = PackageManager.GET_SIGNATURES;
4284 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4285 } catch (NameNotFoundException e) {
4286 Slog.e(TAG, "Invalid package restoring data", e);
4287 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4288 "Package missing on device");
4289 executeNextState(RestoreState.RUNNING_QUEUE);
4290 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004291 }
4292
Christopher Tate2982d062011-09-06 20:35:24 -07004293 if (metaInfo.versionCode > packageInfo.versionCode) {
4294 // Data is from a "newer" version of the app than we have currently
4295 // installed. If the app has not declared that it is prepared to
4296 // handle this case, we do not attempt the restore.
4297 if ((packageInfo.applicationInfo.flags
4298 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4299 String message = "Version " + metaInfo.versionCode
4300 + " > installed version " + packageInfo.versionCode;
4301 Slog.w(TAG, "Package " + packageName + ": " + message);
4302 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4303 packageName, message);
4304 executeNextState(RestoreState.RUNNING_QUEUE);
4305 return;
4306 } else {
4307 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4308 + " > installed " + packageInfo.versionCode
4309 + " but restoreAnyVersion");
4310 }
4311 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004312
Christopher Tate2982d062011-09-06 20:35:24 -07004313 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4314 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4315 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4316 "Signature mismatch");
4317 executeNextState(RestoreState.RUNNING_QUEUE);
4318 return;
4319 }
4320
4321 if (DEBUG) Slog.v(TAG, "Package " + packageName
4322 + " restore version [" + metaInfo.versionCode
4323 + "] is compatible with installed version ["
4324 + packageInfo.versionCode + "]");
4325
4326 // Then set up and bind the agent
4327 IBackupAgent agent = bindToAgentSynchronous(
4328 packageInfo.applicationInfo,
4329 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4330 if (agent == null) {
4331 Slog.w(TAG, "Can't find backup agent for " + packageName);
4332 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4333 "Restore agent missing");
4334 executeNextState(RestoreState.RUNNING_QUEUE);
4335 return;
4336 }
4337
4338 // And then finally start the restore on this agent
4339 try {
4340 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4341 ++mCount;
4342 } catch (Exception e) {
4343 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4344 agentErrorCleanup();
4345 executeNextState(RestoreState.RUNNING_QUEUE);
4346 }
4347 } catch (RemoteException e) {
4348 Slog.e(TAG, "Unable to fetch restore data from transport");
4349 mStatus = BackupConstants.TRANSPORT_ERROR;
4350 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004351 }
4352 }
4353
Christopher Tate2982d062011-09-06 20:35:24 -07004354 void finalizeRestore() {
4355 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4356
4357 try {
4358 mTransport.finishRestore();
4359 } catch (RemoteException e) {
4360 Slog.e(TAG, "Error finishing restore", e);
4361 }
4362
4363 if (mObserver != null) {
4364 try {
4365 mObserver.restoreFinished(mStatus);
4366 } catch (RemoteException e) {
4367 Slog.d(TAG, "Restore observer died at restoreFinished");
4368 }
4369 }
4370
4371 // If this was a restoreAll operation, record that this was our
4372 // ancestral dataset, as well as the set of apps that are possibly
4373 // restoreable from the dataset
4374 if (mTargetPackage == null && mPmAgent != null) {
4375 mAncestralPackages = mPmAgent.getRestoredPackages();
4376 mAncestralToken = mToken;
4377 writeRestoreTokens();
4378 }
4379
4380 // We must under all circumstances tell the Package Manager to
4381 // proceed with install notifications if it's waiting for us.
4382 if (mPmToken > 0) {
4383 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4384 try {
4385 mPackageManagerBinder.finishPackageInstall(mPmToken);
4386 } catch (RemoteException e) { /* can't happen */ }
4387 }
4388
4389 // Furthermore we need to reset the session timeout clock
4390 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4391 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4392 TIMEOUT_RESTORE_INTERVAL);
4393
4394 // done; we can finally release the wakelock
4395 Slog.i(TAG, "Restore complete.");
4396 mWakelock.release();
4397 }
4398
4399 // Call asynchronously into the app, passing it the restore data. The next step
4400 // after this is always a callback, either operationComplete() or handleTimeout().
4401 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004402 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004403 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004404 final String packageName = app.packageName;
4405
Christopher Tate2982d062011-09-06 20:35:24 -07004406 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004407
Christopher Tatec7b31e32009-06-10 15:49:30 -07004408 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004409 mBackupDataName = new File(mDataDir, packageName + ".restore");
4410 mNewStateName = new File(mStateDir, packageName + ".new");
4411 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004412
Christopher Tate4a627c72011-04-01 14:43:32 -07004413 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004414 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004415 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004416 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004417 ParcelFileDescriptor.MODE_READ_WRITE |
4418 ParcelFileDescriptor.MODE_CREATE |
4419 ParcelFileDescriptor.MODE_TRUNCATE);
4420
Christopher Tate2982d062011-09-06 20:35:24 -07004421 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004422 // Transport-level failure, so we wind everything up and
4423 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004424 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004425 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004426 mBackupData.close();
4427 mBackupDataName.delete();
4428 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004429 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004430 }
4431
4432 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004433 mBackupData.close();
4434 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004435 ParcelFileDescriptor.MODE_READ_ONLY);
4436
Christopher Tate2982d062011-09-06 20:35:24 -07004437 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004438 ParcelFileDescriptor.MODE_READ_WRITE |
4439 ParcelFileDescriptor.MODE_CREATE |
4440 ParcelFileDescriptor.MODE_TRUNCATE);
4441
Christopher Tate44a27902010-01-27 17:15:49 -08004442 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004443 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4444 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004445 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004446 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004447 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004448 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004449
Christopher Tate2982d062011-09-06 20:35:24 -07004450 // After a restore failure we go back to running the queue. If there
4451 // are no more packages to be restored that will be handled by the
4452 // next step.
4453 executeNextState(RestoreState.RUNNING_QUEUE);
4454 }
4455 }
Chris Tate249345b2010-10-29 12:57:04 -07004456
Christopher Tate2982d062011-09-06 20:35:24 -07004457 void agentErrorCleanup() {
4458 // If the agent fails restore, it might have put the app's data
4459 // into an incoherent state. For consistency we wipe its data
4460 // again in this case before continuing with normal teardown
4461 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4462 agentCleanup();
4463 }
4464
4465 void agentCleanup() {
4466 mBackupDataName.delete();
4467 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4468 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4469 mBackupData = mNewState = null;
4470
4471 // if everything went okay, remember the recorded state now
4472 //
4473 // !!! TODO: the restored data should be migrated on the server
4474 // side into the current dataset. In that case the new state file
4475 // we just created would reflect the data already extant in the
4476 // backend, so there'd be nothing more to do. Until that happens,
4477 // however, we need to make sure that we record the data to the
4478 // current backend dataset. (Yes, this means shipping the data over
4479 // the wire in both directions. That's bad, but consistency comes
4480 // first, then efficiency.) Once we introduce server-side data
4481 // migration to the newly-restored device's dataset, we will change
4482 // the following from a discard of the newly-written state to the
4483 // "correct" operation of renaming into the canonical state blob.
4484 mNewStateName.delete(); // TODO: remove; see above comment
4485 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4486
4487 // If this wasn't the PM pseudopackage, tear down the agent side
4488 if (mCurrentPackage.applicationInfo != null) {
4489 // unbind and tidy up even on timeout or failure
4490 try {
4491 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4492
4493 // The agent was probably running with a stub Application object,
4494 // which isn't a valid run mode for the main app logic. Shut
4495 // down the app so that next time it's launched, it gets the
4496 // usual full initialization. Note that this is only done for
4497 // full-system restores: when a single app has requested a restore,
4498 // it is explicitly not killed following that operation.
4499 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4500 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4501 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4502 + mCurrentPackage.applicationInfo.processName);
4503 mActivityManager.killApplicationProcess(
4504 mCurrentPackage.applicationInfo.processName,
4505 mCurrentPackage.applicationInfo.uid);
4506 }
4507 } catch (RemoteException e) {
4508 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004509 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004510 }
Christopher Tate2982d062011-09-06 20:35:24 -07004511
4512 // The caller is responsible for reestablishing the state machine; our
4513 // responsibility here is to clear the decks for whatever comes next.
4514 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4515 synchronized (mCurrentOpLock) {
4516 mCurrentOperations.clear();
4517 }
4518 }
4519
4520 // A call to agent.doRestore() has been positively acknowledged as complete
4521 @Override
4522 public void operationComplete() {
4523 int size = (int) mBackupDataName.length();
4524 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4525 // Just go back to running the restore queue
4526 agentCleanup();
4527
4528 executeNextState(RestoreState.RUNNING_QUEUE);
4529 }
4530
4531 // A call to agent.doRestore() has timed out
4532 @Override
4533 public void handleTimeout() {
4534 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4535 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4536 mCurrentPackage.packageName, "restore timeout");
4537 // Handle like an agent that threw on invocation: wipe it and go on to the next
4538 agentErrorCleanup();
4539 executeNextState(RestoreState.RUNNING_QUEUE);
4540 }
4541
4542 void executeNextState(RestoreState nextState) {
4543 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4544 + this + " nextState=" + nextState);
4545 mCurrentState = nextState;
4546 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4547 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004548 }
4549 }
4550
Christopher Tate44a27902010-01-27 17:15:49 -08004551 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004552 IBackupTransport mTransport;
4553 PackageInfo mPackage;
4554
Christopher Tate44a27902010-01-27 17:15:49 -08004555 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004556 mTransport = transport;
4557 mPackage = packageInfo;
4558 }
4559
Christopher Tateee0e78a2009-07-02 11:17:03 -07004560 public void run() {
4561 try {
4562 // Clear the on-device backup state to ensure a full backup next time
4563 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4564 File stateFile = new File(stateDir, mPackage.packageName);
4565 stateFile.delete();
4566
4567 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004568 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004569 mTransport.clearBackupData(mPackage);
4570 } catch (RemoteException e) {
4571 // can't happen; the transport is local
4572 } finally {
4573 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004574 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004575 mTransport.finishBackup();
4576 } catch (RemoteException e) {
4577 // can't happen; the transport is local
4578 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004579
4580 // Last but not least, release the cpu
4581 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004582 }
4583 }
4584 }
4585
Christopher Tate44a27902010-01-27 17:15:49 -08004586 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004587 HashSet<String> mQueue;
4588
Christopher Tate44a27902010-01-27 17:15:49 -08004589 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004590 mQueue = transportNames;
4591 }
4592
Christopher Tate4cc86e12009-09-21 19:36:51 -07004593 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004594 try {
4595 for (String transportName : mQueue) {
4596 IBackupTransport transport = getTransport(transportName);
4597 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004598 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004599 continue;
4600 }
4601
Joe Onorato8a9b2202010-02-26 18:56:32 -08004602 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004603 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004604 long startRealtime = SystemClock.elapsedRealtime();
4605 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004606
Christopher Tate4cc86e12009-09-21 19:36:51 -07004607 if (status == BackupConstants.TRANSPORT_OK) {
4608 status = transport.finishBackup();
4609 }
4610
4611 // Okay, the wipe really happened. Clean up our local bookkeeping.
4612 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004613 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004614 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004615 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004616 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004617 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004618 synchronized (mQueueLock) {
4619 recordInitPendingLocked(false, transportName);
4620 }
Dan Egnor726247c2009-09-29 19:12:31 -07004621 } else {
4622 // If this didn't work, requeue this one and try again
4623 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004624 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004625 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004626 synchronized (mQueueLock) {
4627 recordInitPendingLocked(true, transportName);
4628 }
4629 // do this via another alarm to make sure of the wakelock states
4630 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004631 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004632 + transportName + " resched in " + delay);
4633 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4634 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004635 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004636 }
4637 } catch (RemoteException e) {
4638 // can't happen; the transports are local
4639 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004640 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004641 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004642 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004643 mWakelock.release();
4644 }
4645 }
4646 }
4647
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004648 private void dataChangedImpl(String packageName) {
4649 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4650 dataChangedImpl(packageName, targets);
4651 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004652
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004653 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004654 // Record that we need a backup pass for the caller. Since multiple callers
4655 // may share a uid, we need to note all candidates within that uid and schedule
4656 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004657 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004658
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004659 if (targets == null) {
4660 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4661 + " uid=" + Binder.getCallingUid());
4662 return;
4663 }
4664
4665 synchronized (mQueueLock) {
4666 // Note that this client has made data changes that need to be backed up
4667 for (ApplicationInfo app : targets) {
4668 // validate the caller-supplied package name against the known set of
4669 // packages associated with this uid
4670 if (app.packageName.equals(packageName)) {
4671 // Add the caller to the set of pending backups. If there is
4672 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004673 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004674 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004675 // Journal this request in case of crash. The put()
4676 // operation returned null when this package was not already
4677 // in the set; we want to avoid touching the disk redundantly.
4678 writeToJournalLocked(packageName);
4679
Christopher Tatec58efa62011-08-01 19:20:14 -07004680 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004681 int numKeys = mPendingBackups.size();
4682 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4683 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004684 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004685 }
4686 }
4687 }
4688 }
4689 }
4690 }
4691 }
4692
4693 // Note: packageName is currently unused, but may be in the future
4694 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004695 // If the caller does not hold the BACKUP permission, it can only request a
4696 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004697 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004698 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004699 synchronized (mBackupParticipants) {
4700 return mBackupParticipants.get(Binder.getCallingUid());
4701 }
4702 }
4703
4704 // a caller with full permission can ask to back up any participating app
4705 // !!! TODO: allow backup of ANY app?
4706 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4707 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004708 int N = mBackupParticipants.size();
4709 for (int i = 0; i < N; i++) {
4710 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4711 if (s != null) {
4712 targets.addAll(s);
4713 }
4714 }
4715 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004716 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004717 }
Christopher Tate46758122009-05-06 11:22:00 -07004718
Christopher Tatecde87f42009-06-12 12:55:53 -07004719 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004720 RandomAccessFile out = null;
4721 try {
4722 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4723 out = new RandomAccessFile(mJournal, "rws");
4724 out.seek(out.length());
4725 out.writeUTF(str);
4726 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004727 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004728 mJournal = null;
4729 } finally {
4730 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004731 }
4732 }
4733
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004734 // ----- IBackupManager binder interface -----
4735
4736 public void dataChanged(final String packageName) {
4737 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4738 if (targets == null) {
4739 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4740 + " uid=" + Binder.getCallingUid());
4741 return;
4742 }
4743
4744 mBackupHandler.post(new Runnable() {
4745 public void run() {
4746 dataChangedImpl(packageName, targets);
4747 }
4748 });
4749 }
4750
Christopher Tateee0e78a2009-07-02 11:17:03 -07004751 // Clear the given package's backup data from the current transport
4752 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004753 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004754 PackageInfo info;
4755 try {
4756 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4757 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004758 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004759 return;
4760 }
4761
4762 // If the caller does not hold the BACKUP permission, it can only request a
4763 // wipe of its own backed-up data.
4764 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004765 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004766 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4767 apps = mBackupParticipants.get(Binder.getCallingUid());
4768 } else {
4769 // a caller with full permission can ask to back up any participating app
4770 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004771 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004772 apps = new HashSet<ApplicationInfo>();
4773 int N = mBackupParticipants.size();
4774 for (int i = 0; i < N; i++) {
4775 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4776 if (s != null) {
4777 apps.addAll(s);
4778 }
4779 }
4780 }
4781
4782 // now find the given package in the set of candidate apps
4783 for (ApplicationInfo app : apps) {
4784 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004785 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004786 // found it; fire off the clear request
4787 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004788 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004789 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004790 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4791 new ClearParams(getTransport(mCurrentTransport), info));
4792 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004793 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004794 }
4795 break;
4796 }
4797 }
4798 }
4799
Christopher Tateace7f092009-06-15 18:07:25 -07004800 // Run a backup pass immediately for any applications that have declared
4801 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004802 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004804
Joe Onorato8a9b2202010-02-26 18:56:32 -08004805 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004806 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004807 // Because the alarms we are using can jitter, and we want an *immediate*
4808 // backup pass to happen, we restart the timer beginning with "next time,"
4809 // then manually fire the backup trigger intent ourselves.
4810 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004811 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004812 mRunBackupIntent.send();
4813 } catch (PendingIntent.CanceledException e) {
4814 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004815 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004816 }
Christopher Tate46758122009-05-06 11:22:00 -07004817 }
4818 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004819
Christopher Tated2c0cd42011-09-15 15:51:29 -07004820 boolean deviceIsProvisioned() {
4821 final ContentResolver resolver = mContext.getContentResolver();
4822 return (Settings.Secure.getInt(resolver, Settings.Secure.DEVICE_PROVISIONED, 0) != 0);
4823 }
4824
Christopher Tate4a627c72011-04-01 14:43:32 -07004825 // Run a *full* backup pass for the given package, writing the resulting data stream
4826 // to the supplied file descriptor. This method is synchronous and does not return
4827 // to the caller until the backup has been completed.
4828 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004829 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004830 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4831
4832 // Validate
4833 if (!doAllApps) {
4834 if (!includeShared) {
4835 // If we're backing up shared data (sdcard or equivalent), then we can run
4836 // without any supplied app names. Otherwise, we'd be doing no work, so
4837 // report the error.
4838 if (pkgList == null || pkgList.length == 0) {
4839 throw new IllegalArgumentException(
4840 "Backup requested but neither shared nor any apps named");
4841 }
4842 }
4843 }
4844
Christopher Tate4a627c72011-04-01 14:43:32 -07004845 long oldId = Binder.clearCallingIdentity();
4846 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004847 // Doesn't make sense to do a full backup prior to setup
4848 if (!deviceIsProvisioned()) {
4849 Slog.i(TAG, "Full backup not supported before setup");
4850 return;
4851 }
4852
4853 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4854 + " shared=" + includeShared + " all=" + doAllApps
4855 + " pkgs=" + pkgList);
4856 Slog.i(TAG, "Beginning full backup...");
4857
Christopher Tate4a627c72011-04-01 14:43:32 -07004858 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004859 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07004860 final int token = generateToken();
4861 synchronized (mFullConfirmations) {
4862 mFullConfirmations.put(token, params);
4863 }
4864
Christopher Tate75a99702011-05-18 16:28:19 -07004865 // start up the confirmation UI
4866 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4867 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4868 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004869 mFullConfirmations.delete(token);
4870 return;
4871 }
Christopher Tate75a99702011-05-18 16:28:19 -07004872
4873 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004874 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4875
4876 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004877 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004878
4879 // wait for the backup to be performed
4880 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4881 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004882 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004883 try {
4884 fd.close();
4885 } catch (IOException e) {
4886 // just eat it
4887 }
Christopher Tate75a99702011-05-18 16:28:19 -07004888 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004889 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07004890 }
Christopher Tate75a99702011-05-18 16:28:19 -07004891 }
4892
4893 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004894 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004895
4896 long oldId = Binder.clearCallingIdentity();
4897
4898 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004899 // Check whether the device has been provisioned -- we don't handle
4900 // full restores prior to completing the setup process.
4901 if (!deviceIsProvisioned()) {
4902 Slog.i(TAG, "Full restore not permitted before setup");
4903 return;
4904 }
4905
4906 Slog.i(TAG, "Beginning full restore...");
4907
Christopher Tate75a99702011-05-18 16:28:19 -07004908 FullRestoreParams params = new FullRestoreParams(fd);
4909 final int token = generateToken();
4910 synchronized (mFullConfirmations) {
4911 mFullConfirmations.put(token, params);
4912 }
4913
4914 // start up the confirmation UI
4915 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4916 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4917 Slog.e(TAG, "Unable to launch full restore confirmation");
4918 mFullConfirmations.delete(token);
4919 return;
4920 }
4921
4922 // make sure the screen is lit for the user interaction
4923 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4924
4925 // start the confirmation countdown
4926 startConfirmationTimeout(token, params);
4927
4928 // wait for the restore to be performed
4929 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4930 waitForCompletion(params);
4931 } finally {
4932 try {
4933 fd.close();
4934 } catch (IOException e) {
4935 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4936 }
4937 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004938 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07004939 }
4940 }
4941
4942 boolean startConfirmationUi(int token, String action) {
4943 try {
4944 Intent confIntent = new Intent(action);
4945 confIntent.setClassName("com.android.backupconfirm",
4946 "com.android.backupconfirm.BackupRestoreConfirmation");
4947 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4948 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4949 mContext.startActivity(confIntent);
4950 } catch (ActivityNotFoundException e) {
4951 return false;
4952 }
4953 return true;
4954 }
4955
4956 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004957 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004958 + TIMEOUT_FULL_CONFIRMATION + " millis");
4959 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4960 token, 0, params);
4961 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004962 }
4963
4964 void waitForCompletion(FullParams params) {
4965 synchronized (params.latch) {
4966 while (params.latch.get() == false) {
4967 try {
4968 params.latch.wait();
4969 } catch (InterruptedException e) { /* never interrupted */ }
4970 }
4971 }
4972 }
4973
4974 void signalFullBackupRestoreCompletion(FullParams params) {
4975 synchronized (params.latch) {
4976 params.latch.set(true);
4977 params.latch.notifyAll();
4978 }
4979 }
4980
4981 // Confirm that the previously-requested full backup/restore operation can proceed. This
4982 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004983 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004984 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004985 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004986 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4987 + " allow=" + allow);
4988
4989 // TODO: possibly require not just this signature-only permission, but even
4990 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004991 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004992
4993 long oldId = Binder.clearCallingIdentity();
4994 try {
4995
4996 FullParams params;
4997 synchronized (mFullConfirmations) {
4998 params = mFullConfirmations.get(token);
4999 if (params != null) {
5000 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
5001 mFullConfirmations.delete(token);
5002
5003 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07005004 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07005005 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07005006 : MSG_RUN_FULL_RESTORE;
5007
Christopher Tate728a1c42011-07-28 18:03:03 -07005008 params.observer = observer;
5009 params.curPassword = curPassword;
5010 params.encryptPassword = encPpassword;
5011
Christopher Tate75a99702011-05-18 16:28:19 -07005012 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005013 mWakelock.acquire();
5014 Message msg = mBackupHandler.obtainMessage(verb, params);
5015 mBackupHandler.sendMessage(msg);
5016 } else {
5017 Slog.w(TAG, "User rejected full backup/restore operation");
5018 // indicate completion without having actually transferred any data
5019 signalFullBackupRestoreCompletion(params);
5020 }
5021 } else {
5022 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5023 }
5024 }
5025 } finally {
5026 Binder.restoreCallingIdentity(oldId);
5027 }
5028 }
5029
Christopher Tate8031a3d2009-07-06 16:36:05 -07005030 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005031 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005032 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005033 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005034
Joe Onorato8a9b2202010-02-26 18:56:32 -08005035 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005036
Christopher Tate6ef58a12009-06-29 14:56:28 -07005037 boolean wasEnabled = mEnabled;
5038 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005039 Settings.Secure.putInt(mContext.getContentResolver(),
5040 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005041 mEnabled = enable;
5042 }
5043
Christopher Tate49401dd2009-07-01 12:34:29 -07005044 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005045 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005046 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005047 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005048 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005049 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005050 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005051
Christopher Tateb6787f22009-07-02 17:40:45 -07005052 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005053
5054 // This also constitutes an opt-out, so we wipe any data for
5055 // this device from the backend. We start that process with
5056 // an alarm in order to guarantee wakelock states.
5057 if (wasEnabled && mProvisioned) {
5058 // NOTE: we currently flush every registered transport, not just
5059 // the currently-active one.
5060 HashSet<String> allTransports;
5061 synchronized (mTransports) {
5062 allTransports = new HashSet<String>(mTransports.keySet());
5063 }
5064 // build the set of transports for which we are posting an init
5065 for (String transport : allTransports) {
5066 recordInitPendingLocked(true, transport);
5067 }
5068 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5069 mRunInitIntent);
5070 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005071 }
5072 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005073 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005074
Christopher Tatecce9da52010-02-03 15:11:15 -08005075 // Enable/disable automatic restore of app data at install time
5076 public void setAutoRestore(boolean doAutoRestore) {
5077 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005078 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005079
Joe Onorato8a9b2202010-02-26 18:56:32 -08005080 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005081
5082 synchronized (this) {
5083 Settings.Secure.putInt(mContext.getContentResolver(),
5084 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5085 mAutoRestore = doAutoRestore;
5086 }
5087 }
5088
Christopher Tate8031a3d2009-07-06 16:36:05 -07005089 // Mark the backup service as having been provisioned
5090 public void setBackupProvisioned(boolean available) {
5091 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5092 "setBackupProvisioned");
5093
5094 boolean wasProvisioned = mProvisioned;
5095 synchronized (this) {
5096 Settings.Secure.putInt(mContext.getContentResolver(),
5097 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
5098 mProvisioned = available;
5099 }
5100
5101 synchronized (mQueueLock) {
5102 if (available && !wasProvisioned && mEnabled) {
5103 // we're now good to go, so start the backup alarms
5104 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
5105 } else if (!available) {
5106 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005107 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07005108 mAlarmManager.cancel(mRunBackupIntent);
5109 }
5110 }
5111 }
5112
5113 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005114 // We used to use setInexactRepeating(), but that may be linked to
5115 // backups running at :00 more often than not, creating load spikes.
5116 // Schedule at an exact time for now, and also add a bit of "fuzz".
5117
5118 Random random = new Random();
5119 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5120 random.nextInt(FUZZ_MILLIS);
5121 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5122 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005123 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005124 }
5125
Christopher Tate6ef58a12009-06-29 14:56:28 -07005126 // Report whether the backup mechanism is currently enabled
5127 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005128 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005129 return mEnabled; // no need to synchronize just to read it
5130 }
5131
Christopher Tate91717492009-06-26 21:07:13 -07005132 // Report the name of the currently active transport
5133 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005134 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005135 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005136 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005137 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005138 }
5139
Christopher Tate91717492009-06-26 21:07:13 -07005140 // Report all known, available backup transports
5141 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005142 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005143
Christopher Tate91717492009-06-26 21:07:13 -07005144 String[] list = null;
5145 ArrayList<String> known = new ArrayList<String>();
5146 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5147 if (entry.getValue() != null) {
5148 known.add(entry.getKey());
5149 }
5150 }
5151
5152 if (known.size() > 0) {
5153 list = new String[known.size()];
5154 known.toArray(list);
5155 }
5156 return list;
5157 }
5158
5159 // Select which transport to use for the next backup operation. If the given
5160 // name is not one of the available transports, no action is taken and the method
5161 // returns null.
5162 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005163 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005164
5165 synchronized (mTransports) {
5166 String prevTransport = null;
5167 if (mTransports.get(transport) != null) {
5168 prevTransport = mCurrentTransport;
5169 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005170 Settings.Secure.putString(mContext.getContentResolver(),
5171 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005172 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005173 + " returning " + prevTransport);
5174 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005175 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005176 }
5177 return prevTransport;
5178 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005179 }
5180
Christopher Tatef5e1c292010-12-08 18:40:26 -08005181 // Supply the configuration Intent for the given transport. If the name is not one
5182 // of the available transports, or if the transport does not supply any configuration
5183 // UI, the method returns null.
5184 public Intent getConfigurationIntent(String transportName) {
5185 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5186 "getConfigurationIntent");
5187
5188 synchronized (mTransports) {
5189 final IBackupTransport transport = mTransports.get(transportName);
5190 if (transport != null) {
5191 try {
5192 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005193 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005194 + intent);
5195 return intent;
5196 } catch (RemoteException e) {
5197 /* fall through to return null */
5198 }
5199 }
5200 }
5201
5202 return null;
5203 }
5204
5205 // Supply the configuration summary string for the given transport. If the name is
5206 // not one of the available transports, or if the transport does not supply any
5207 // summary / destination string, the method can return null.
5208 //
5209 // This string is used VERBATIM as the summary text of the relevant Settings item!
5210 public String getDestinationString(String transportName) {
5211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005212 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005213
5214 synchronized (mTransports) {
5215 final IBackupTransport transport = mTransports.get(transportName);
5216 if (transport != null) {
5217 try {
5218 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005219 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005220 return text;
5221 } catch (RemoteException e) {
5222 /* fall through to return null */
5223 }
5224 }
5225 }
5226
5227 return null;
5228 }
5229
Christopher Tate043dadc2009-06-02 16:11:00 -07005230 // Callback: a requested backup agent has been instantiated. This should only
5231 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005232 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005233 synchronized(mAgentConnectLock) {
5234 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005235 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005236 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5237 mConnectedAgent = agent;
5238 mConnecting = false;
5239 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005240 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005241 + " claiming agent connected");
5242 }
5243 mAgentConnectLock.notifyAll();
5244 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005245 }
5246
5247 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5248 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005249 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005250 public void agentDisconnected(String packageName) {
5251 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005252 synchronized(mAgentConnectLock) {
5253 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5254 mConnectedAgent = null;
5255 mConnecting = false;
5256 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005257 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005258 + " claiming agent disconnected");
5259 }
5260 mAgentConnectLock.notifyAll();
5261 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005262 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005263
Christopher Tate1bb69062010-02-19 17:02:12 -08005264 // An application being installed will need a restore pass, then the Package Manager
5265 // will need to be told when the restore is finished.
5266 public void restoreAtInstall(String packageName, int token) {
5267 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005268 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005269 + " attemping install-time restore");
5270 return;
5271 }
5272
5273 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005274 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005275 + " token=" + Integer.toHexString(token));
5276
Christopher Tatef0872722010-02-25 15:22:48 -08005277 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005278 // okay, we're going to attempt a restore of this package from this restore set.
5279 // The eventual message back into the Package Manager to run the post-install
5280 // steps for 'token' will be issued from the restore handling code.
5281
5282 // We can use a synthetic PackageInfo here because:
5283 // 1. We know it's valid, since the Package Manager supplied the name
5284 // 2. Only the packageName field will be used by the restore code
5285 PackageInfo pkg = new PackageInfo();
5286 pkg.packageName = packageName;
5287
5288 mWakelock.acquire();
5289 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5290 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005291 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005292 mBackupHandler.sendMessage(msg);
5293 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005294 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5295 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005296 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005297 try {
5298 mPackageManagerBinder.finishPackageInstall(token);
5299 } catch (RemoteException e) { /* can't happen */ }
5300 }
5301 }
5302
Christopher Tate8c850b72009-06-07 19:33:20 -07005303 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005304 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5305 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5306 + " transport=" + transport);
5307
5308 boolean needPermission = true;
5309 if (transport == null) {
5310 transport = mCurrentTransport;
5311
5312 if (packageName != null) {
5313 PackageInfo app = null;
5314 try {
5315 app = mPackageManager.getPackageInfo(packageName, 0);
5316 } catch (NameNotFoundException nnf) {
5317 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5318 throw new IllegalArgumentException("Package " + packageName + " not found");
5319 }
5320
5321 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5322 // So: using the current active transport, and the caller has asked
5323 // that its own package will be restored. In this narrow use case
5324 // we do not require the caller to hold the permission.
5325 needPermission = false;
5326 }
5327 }
5328 }
5329
5330 if (needPermission) {
5331 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5332 "beginRestoreSession");
5333 } else {
5334 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5335 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005336
5337 synchronized(this) {
5338 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005339 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005340 return null;
5341 }
Chris Tate44ab8452010-11-16 15:10:49 -08005342 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005343 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005344 }
5345 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005346 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005347
Christopher Tate73a3cb32010-12-13 18:27:26 -08005348 void clearRestoreSession(ActiveRestoreSession currentSession) {
5349 synchronized(this) {
5350 if (currentSession != mActiveRestoreSession) {
5351 Slog.e(TAG, "ending non-current restore session");
5352 } else {
5353 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5354 mActiveRestoreSession = null;
5355 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5356 }
5357 }
5358 }
5359
Christopher Tate44a27902010-01-27 17:15:49 -08005360 // Note that a currently-active backup agent has notified us that it has
5361 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005362 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005363 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005364 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5365 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005366 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005367 op = mCurrentOperations.get(token);
5368 if (op != null) {
5369 op.state = OP_ACKNOWLEDGED;
5370 }
Christopher Tate44a27902010-01-27 17:15:49 -08005371 mCurrentOpLock.notifyAll();
5372 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005373
5374 // The completion callback, if any, is invoked on the handler
5375 if (op != null && op.callback != null) {
5376 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5377 mBackupHandler.sendMessage(msg);
5378 }
Christopher Tate44a27902010-01-27 17:15:49 -08005379 }
5380
Christopher Tate9b3905c2009-06-08 15:24:01 -07005381 // ----- Restore session -----
5382
Christopher Tate80202c82010-01-25 19:37:47 -08005383 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005384 private static final String TAG = "RestoreSession";
5385
Chris Tate44ab8452010-11-16 15:10:49 -08005386 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005387 private IBackupTransport mRestoreTransport = null;
5388 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005389 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005390
Chris Tate44ab8452010-11-16 15:10:49 -08005391 ActiveRestoreSession(String packageName, String transport) {
5392 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005393 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005394 }
5395
5396 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005397 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005398 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005399 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005400 if (observer == null) {
5401 throw new IllegalArgumentException("Observer must not be null");
5402 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005403
Christopher Tate73a3cb32010-12-13 18:27:26 -08005404 if (mEnded) {
5405 throw new IllegalStateException("Restore session already ended");
5406 }
5407
Christopher Tate1bb69062010-02-19 17:02:12 -08005408 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005409 try {
Christopher Tate43383042009-07-13 15:17:13 -07005410 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005411 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005412 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005413 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005414 // spin off the transport request to our service thread
5415 mWakelock.acquire();
5416 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5417 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5418 mBackupHandler.sendMessage(msg);
5419 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005420 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005421 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005422 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005423 } finally {
5424 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005425 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005426 }
5427
Christopher Tate84725812010-02-04 15:52:40 -08005428 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005429 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5430 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005431
Chris Tate44ab8452010-11-16 15:10:49 -08005432 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005433 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005434
Christopher Tate73a3cb32010-12-13 18:27:26 -08005435 if (mEnded) {
5436 throw new IllegalStateException("Restore session already ended");
5437 }
5438
Dan Egnor0084da52009-07-29 12:57:16 -07005439 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005440 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5441 return -1;
5442 }
5443
5444 if (mPackageName != null) {
5445 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005446 return -1;
5447 }
5448
Christopher Tate21ab6a52009-09-24 18:01:46 -07005449 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005450 for (int i = 0; i < mRestoreSets.length; i++) {
5451 if (token == mRestoreSets[i].token) {
5452 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005453 mWakelock.acquire();
5454 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005455 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005456 mBackupHandler.sendMessage(msg);
5457 Binder.restoreCallingIdentity(oldId);
5458 return 0;
5459 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005460 }
5461 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005462
Joe Onorato8a9b2202010-02-26 18:56:32 -08005463 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005464 return -1;
5465 }
5466
Christopher Tate284f1bb2011-07-07 14:31:18 -07005467 public synchronized int restoreSome(long token, IRestoreObserver observer,
5468 String[] packages) {
5469 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5470 "performRestore");
5471
5472 if (DEBUG) {
5473 StringBuilder b = new StringBuilder(128);
5474 b.append("restoreSome token=");
5475 b.append(Long.toHexString(token));
5476 b.append(" observer=");
5477 b.append(observer.toString());
5478 b.append(" packages=");
5479 if (packages == null) {
5480 b.append("null");
5481 } else {
5482 b.append('{');
5483 boolean first = true;
5484 for (String s : packages) {
5485 if (!first) {
5486 b.append(", ");
5487 } else first = false;
5488 b.append(s);
5489 }
5490 b.append('}');
5491 }
5492 Slog.d(TAG, b.toString());
5493 }
5494
5495 if (mEnded) {
5496 throw new IllegalStateException("Restore session already ended");
5497 }
5498
5499 if (mRestoreTransport == null || mRestoreSets == null) {
5500 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5501 return -1;
5502 }
5503
5504 if (mPackageName != null) {
5505 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5506 return -1;
5507 }
5508
5509 synchronized (mQueueLock) {
5510 for (int i = 0; i < mRestoreSets.length; i++) {
5511 if (token == mRestoreSets[i].token) {
5512 long oldId = Binder.clearCallingIdentity();
5513 mWakelock.acquire();
5514 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5515 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5516 packages, true);
5517 mBackupHandler.sendMessage(msg);
5518 Binder.restoreCallingIdentity(oldId);
5519 return 0;
5520 }
5521 }
5522 }
5523
5524 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5525 return -1;
5526 }
5527
Christopher Tate84725812010-02-04 15:52:40 -08005528 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005529 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005530
Christopher Tate73a3cb32010-12-13 18:27:26 -08005531 if (mEnded) {
5532 throw new IllegalStateException("Restore session already ended");
5533 }
5534
Chris Tate44ab8452010-11-16 15:10:49 -08005535 if (mPackageName != null) {
5536 if (! mPackageName.equals(packageName)) {
5537 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5538 + " on session for package " + mPackageName);
5539 return -1;
5540 }
5541 }
5542
Christopher Tate84725812010-02-04 15:52:40 -08005543 PackageInfo app = null;
5544 try {
5545 app = mPackageManager.getPackageInfo(packageName, 0);
5546 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005547 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005548 return -1;
5549 }
5550
5551 // If the caller is not privileged and is not coming from the target
5552 // app's uid, throw a permission exception back to the caller.
5553 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5554 Binder.getCallingPid(), Binder.getCallingUid());
5555 if ((perm == PackageManager.PERMISSION_DENIED) &&
5556 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005557 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005558 + " or calling uid=" + Binder.getCallingUid());
5559 throw new SecurityException("No permission to restore other packages");
5560 }
5561
Christopher Tate7d411a32010-02-26 11:27:08 -08005562 // If the package has no backup agent, we obviously cannot proceed
5563 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005564 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005565 return -1;
5566 }
5567
Christopher Tate84725812010-02-04 15:52:40 -08005568 // So far so good; we're allowed to try to restore this package. Now
5569 // check whether there is data for it in the current dataset, falling back
5570 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005571 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005572
5573 // If we didn't come up with a place to look -- no ancestral dataset and
5574 // the app has never been backed up from this device -- there's nothing
5575 // to do but return failure.
5576 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005577 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005578 return -1;
5579 }
5580
5581 // Ready to go: enqueue the restore request and claim success
5582 long oldId = Binder.clearCallingIdentity();
5583 mWakelock.acquire();
5584 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005585 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005586 mBackupHandler.sendMessage(msg);
5587 Binder.restoreCallingIdentity(oldId);
5588 return 0;
5589 }
5590
Christopher Tate73a3cb32010-12-13 18:27:26 -08005591 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5592 class EndRestoreRunnable implements Runnable {
5593 BackupManagerService mBackupManager;
5594 ActiveRestoreSession mSession;
5595
5596 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5597 mBackupManager = manager;
5598 mSession = session;
5599 }
5600
5601 public void run() {
5602 // clean up the session's bookkeeping
5603 synchronized (mSession) {
5604 try {
5605 if (mSession.mRestoreTransport != null) {
5606 mSession.mRestoreTransport.finishRestore();
5607 }
5608 } catch (Exception e) {
5609 Slog.e(TAG, "Error in finishRestore", e);
5610 } finally {
5611 mSession.mRestoreTransport = null;
5612 mSession.mEnded = true;
5613 }
5614 }
5615
5616 // clean up the BackupManagerService side of the bookkeeping
5617 // and cancel any pending timeout message
5618 mBackupManager.clearRestoreSession(mSession);
5619 }
5620 }
5621
Dan Egnor0084da52009-07-29 12:57:16 -07005622 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005623 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005624
Christopher Tate73a3cb32010-12-13 18:27:26 -08005625 if (mEnded) {
5626 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005627 }
5628
Christopher Tate73a3cb32010-12-13 18:27:26 -08005629 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005630 }
5631 }
5632
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005633 @Override
5634 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005635 long identityToken = Binder.clearCallingIdentity();
5636 try {
5637 dumpInternal(pw);
5638 } finally {
5639 Binder.restoreCallingIdentity(identityToken);
5640 }
5641 }
5642
5643 private void dumpInternal(PrintWriter pw) {
Christopher Tateb8491bb2011-09-29 15:13:11 -07005644 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5645 != PackageManager.PERMISSION_GRANTED) {
5646 pw.println("Permission Denial: can't dump Backup Manager service from from pid="
5647 + Binder.getCallingPid()
5648 + ", uid=" + Binder.getCallingUid()
5649 + " without permission "
5650 + android.Manifest.permission.DUMP);
5651 return;
5652 }
5653
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005654 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005655 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005656 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005657 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005658 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005659 if (mBackupRunning) pw.println("Backup currently running");
5660 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005661 + " (now = " + System.currentTimeMillis() + ')');
5662 pw.println(" next scheduled: " + mNextBackupPass);
5663
Christopher Tate91717492009-06-26 21:07:13 -07005664 pw.println("Available transports:");
5665 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005666 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5667 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005668 IBackupTransport transport = getTransport(t);
5669 File dir = new File(mBaseStateDir, transport.transportDirName());
5670 pw.println(" destination: " + transport.currentDestinationString());
5671 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005672 for (File f : dir.listFiles()) {
5673 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5674 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005675 } catch (Exception e) {
5676 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005677 pw.println(" Error: " + e);
5678 }
Christopher Tate91717492009-06-26 21:07:13 -07005679 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005680
5681 pw.println("Pending init: " + mPendingInits.size());
5682 for (String s : mPendingInits) {
5683 pw.println(" " + s);
5684 }
5685
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005686 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005687 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005688 for (int i=0; i<N; i++) {
5689 int uid = mBackupParticipants.keyAt(i);
5690 pw.print(" uid: ");
5691 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005692 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5693 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005694 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005695 }
5696 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005697
Christopher Tateb49ceb32010-02-08 16:22:24 -08005698 pw.println("Ancestral packages: "
5699 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005700 if (mAncestralPackages != null) {
5701 for (String pkg : mAncestralPackages) {
5702 pw.println(" " + pkg);
5703 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005704 }
5705
Christopher Tate73e02522009-07-15 14:18:26 -07005706 pw.println("Ever backed up: " + mEverStoredApps.size());
5707 for (String pkg : mEverStoredApps) {
5708 pw.println(" " + pkg);
5709 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005710
5711 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005712 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005713 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005714 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005715 }
5716 }
Christopher Tate487529a2009-04-29 14:03:25 -07005717}