blob: 5758954794ffbdbd043e8d23c63bc5ec8f13c121 [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) {
1969 backupNow();
1970 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001971 }
1972
1973 // Only once we're entirely finished do we release the wakelock
1974 Slog.i(TAG, "Backup pass finished.");
1975 mWakelock.release();
1976 }
1977
1978 // Invoke an agent's doBackup() and start a timeout message spinning on the main
1979 // handler in case it doesn't get back to us.
1980 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07001981 IBackupTransport transport) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001982 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001983
Christopher Tate8e294d42011-08-31 20:37:12 -07001984 mSavedStateName = new File(mStateDir, packageName);
1985 mBackupDataName = new File(mDataDir, packageName + ".data");
1986 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001987
Christopher Tate8e294d42011-08-31 20:37:12 -07001988 mSavedState = null;
1989 mBackupData = null;
1990 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001991
Christopher Tate4a627c72011-04-01 14:43:32 -07001992 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001993 try {
1994 // Look up the package info & signatures. This is first so that if it
1995 // throws an exception, there's no file setup yet that would need to
1996 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001997 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001998 // The metadata 'package' is synthetic; construct one and make
1999 // sure our global state is pointed at it
2000 mCurrentPackage = new PackageInfo();
2001 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07002002 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002003
Christopher Tatec7b31e32009-06-10 15:49:30 -07002004 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07002005 // the saved-state "file". This is by definition an incremental,
2006 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07002007 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07002008 ParcelFileDescriptor.MODE_READ_ONLY |
2009 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07002010
Christopher Tate8e294d42011-08-31 20:37:12 -07002011 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002012 ParcelFileDescriptor.MODE_READ_WRITE |
2013 ParcelFileDescriptor.MODE_CREATE |
2014 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002015
Christopher Tate8e294d42011-08-31 20:37:12 -07002016 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002017 ParcelFileDescriptor.MODE_READ_WRITE |
2018 ParcelFileDescriptor.MODE_CREATE |
2019 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002020
Christopher Tate44a27902010-01-27 17:15:49 -08002021 // Initiate the target's backup pass
Christopher Tate8e294d42011-08-31 20:37:12 -07002022 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
2023 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002024 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002025 Slog.e(TAG, "Error invoking for backup on " + packageName);
2026 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2027 e.toString());
2028 agentErrorCleanup();
2029 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002030 }
2031
Christopher Tate8e294d42011-08-31 20:37:12 -07002032 // At this point the agent is off and running. The next thing to happen will
2033 // either be a callback from the agent, at which point we'll process its data
2034 // for transport, or a timeout. Either way the next phase will happen in
2035 // response to the TimeoutHandler interface callbacks.
2036 return BackupConstants.TRANSPORT_OK;
2037 }
2038
2039 @Override
2040 public void operationComplete() {
2041 // Okay, the agent successfully reported back to us. Spin the data off to the
2042 // transport and proceed with the next stage.
2043 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2044 + mCurrentPackage.packageName);
2045 mBackupHandler.removeMessages(MSG_TIMEOUT);
2046 clearAgentState();
2047
2048 ParcelFileDescriptor backupData = null;
2049 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002050 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002051 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002052 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002053 if (mStatus == BackupConstants.TRANSPORT_OK) {
2054 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002055 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate8e294d42011-08-31 20:37:12 -07002056 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002057 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002058
Dan Egnor83861e72009-09-17 16:17:55 -07002059 // TODO - We call finishBackup() for each application backed up, because
2060 // we need to know now whether it succeeded or failed. Instead, we should
2061 // hold off on finishBackup() until the end, which implies holding off on
2062 // renaming *all* the output state files (see below) until that happens.
2063
Christopher Tate8e294d42011-08-31 20:37:12 -07002064 if (mStatus == BackupConstants.TRANSPORT_OK) {
2065 mStatus = mTransport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07002066 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002067 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002068 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002069 }
2070
2071 // After successful transport, delete the now-stale data
2072 // and juggle the files so that next time we supply the agent
2073 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002074 if (mStatus == BackupConstants.TRANSPORT_OK) {
2075 mBackupDataName.delete();
2076 mNewStateName.renameTo(mSavedStateName);
2077 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2078 mCurrentPackage.packageName, size);
2079 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002080 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002081 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2082 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002083 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002084 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002085 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2086 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2087 mCurrentPackage.packageName);
2088 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002089 } finally {
2090 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002091 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002092
Christopher Tate8e294d42011-08-31 20:37:12 -07002093 // If we encountered an error here it's a transport-level failure. That
2094 // means we need to halt everything and reschedule everything for next time.
2095 final BackupState nextState;
2096 if (mStatus != BackupConstants.TRANSPORT_OK) {
2097 revertAndEndBackup();
2098 nextState = BackupState.FINAL;
2099 } else {
2100 // Success! Proceed with the next app if any, otherwise we're done.
2101 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2102 }
2103
2104 executeNextState(nextState);
2105 }
2106
2107 @Override
2108 public void handleTimeout() {
2109 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2110 // it for the next time we run a backup pass.
2111 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2112 // fail repeatedly (i.e. have proved themselves to be buggy).
2113 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2114 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2115 "timeout");
2116 agentErrorCleanup();
2117 dataChangedImpl(mCurrentPackage.packageName);
2118 }
2119
2120 void revertAndEndBackup() {
2121 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2122 for (BackupRequest request : mOriginalQueue) {
2123 dataChangedImpl(request.packageName);
2124 }
2125 // We also want to reset the backup schedule based on whatever
2126 // the transport suggests by way of retry/backoff time.
2127 restartBackupAlarm();
2128 }
2129
2130 void agentErrorCleanup() {
2131 mBackupDataName.delete();
2132 mNewStateName.delete();
2133 clearAgentState();
2134
2135 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2136 }
2137
2138 // Cleanup common to both success and failure cases
2139 void clearAgentState() {
2140 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2141 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2142 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2143 mSavedState = mBackupData = mNewState = null;
2144 synchronized (mCurrentOpLock) {
2145 mCurrentOperations.clear();
2146 }
2147
2148 // If this was a pseudopackage there's no associated Activity Manager state
2149 if (mCurrentPackage.applicationInfo != null) {
2150 try { // unbind even on timeout, just in case
2151 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2152 } catch (RemoteException e) {}
2153 }
2154 }
2155
2156 void restartBackupAlarm() {
2157 synchronized (mQueueLock) {
2158 try {
2159 startBackupAlarmsLocked(mTransport.requestBackupTime());
2160 } catch (RemoteException e) { /* cannot happen */ }
2161 }
2162 }
2163
2164 void executeNextState(BackupState nextState) {
2165 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2166 + this + " nextState=" + nextState);
2167 mCurrentState = nextState;
2168 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2169 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002170 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002171 }
2172
Christopher Tatedf01dea2009-06-09 20:45:02 -07002173
Christopher Tate4a627c72011-04-01 14:43:32 -07002174 // ----- Full backup to a file/socket -----
2175
2176 class PerformFullBackupTask implements Runnable {
2177 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002178 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002179 IFullBackupRestoreObserver mObserver;
2180 boolean mIncludeApks;
2181 boolean mIncludeShared;
2182 boolean mAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002183 final boolean mIncludeSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002184 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002185 String mCurrentPassword;
2186 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002187 AtomicBoolean mLatchObject;
2188 File mFilesDir;
2189 File mManifestFile;
2190
Christopher Tate7926a692011-07-11 11:31:57 -07002191 class FullBackupRunner implements Runnable {
2192 PackageInfo mPackage;
2193 IBackupAgent mAgent;
2194 ParcelFileDescriptor mPipe;
2195 int mToken;
2196 boolean mSendApk;
2197
2198 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2199 int token, boolean sendApk) throws IOException {
2200 mPackage = pack;
2201 mAgent = agent;
2202 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2203 mToken = token;
2204 mSendApk = sendApk;
2205 }
2206
2207 @Override
2208 public void run() {
2209 try {
2210 BackupDataOutput output = new BackupDataOutput(
2211 mPipe.getFileDescriptor());
2212
Christopher Tatec58efa62011-08-01 19:20:14 -07002213 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07002214 writeAppManifest(mPackage, mManifestFile, mSendApk);
2215 FullBackup.backupToTar(mPackage.packageName, null, null,
2216 mFilesDir.getAbsolutePath(),
2217 mManifestFile.getAbsolutePath(),
2218 output);
2219
2220 if (mSendApk) {
2221 writeApkToBackup(mPackage, output);
2222 }
2223
Christopher Tatec58efa62011-08-01 19:20:14 -07002224 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002225 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002226 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2227 } catch (IOException e) {
2228 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2229 } catch (RemoteException e) {
2230 Slog.e(TAG, "Remote agent vanished during full backup of "
2231 + mPackage.packageName);
2232 } finally {
2233 try {
2234 mPipe.close();
2235 } catch (IOException e) {}
2236 }
2237 }
2238 }
2239
Christopher Tate4a627c72011-04-01 14:43:32 -07002240 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002241 boolean includeApks, boolean includeShared, String curPassword,
Christopher Tate240c7d22011-10-03 18:13:44 -07002242 String encryptPassword, boolean doAllApps, boolean doSystem, String[] packages,
Christopher Tate728a1c42011-07-28 18:03:03 -07002243 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002244 mOutputFile = fd;
2245 mObserver = observer;
2246 mIncludeApks = includeApks;
2247 mIncludeShared = includeShared;
2248 mAllApps = doAllApps;
Christopher Tate240c7d22011-10-03 18:13:44 -07002249 mIncludeSystem = doSystem;
Christopher Tate4a627c72011-04-01 14:43:32 -07002250 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002251 mCurrentPassword = curPassword;
2252 // when backing up, if there is a current backup password, we require that
2253 // the user use a nonempty encryption password as well. if one is supplied
2254 // in the UI we use that, but if the UI was left empty we fall back to the
2255 // current backup password (which was supplied by the user as well).
2256 if (encryptPassword == null || "".equals(encryptPassword)) {
2257 mEncryptPassword = curPassword;
2258 } else {
2259 mEncryptPassword = encryptPassword;
2260 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002261 mLatchObject = latch;
2262
2263 mFilesDir = new File("/data/system");
2264 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2265 }
2266
2267 @Override
2268 public void run() {
Christopher Tate240c7d22011-10-03 18:13:44 -07002269 List<PackageInfo> packagesToBackup = new ArrayList<PackageInfo>();
Christopher Tate4a627c72011-04-01 14:43:32 -07002270
Christopher Tateb0628bf2011-06-02 15:08:13 -07002271 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002272 sendStartBackup();
2273
2274 // doAllApps supersedes the package set if any
2275 if (mAllApps) {
2276 packagesToBackup = mPackageManager.getInstalledPackages(
2277 PackageManager.GET_SIGNATURES);
Christopher Tate240c7d22011-10-03 18:13:44 -07002278 // Exclude system apps if we've been asked to do so
2279 if (mIncludeSystem == false) {
2280 for (int i = 0; i < packagesToBackup.size(); ) {
2281 PackageInfo pkg = packagesToBackup.get(i);
2282 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2283 packagesToBackup.remove(i);
2284 } else {
2285 i++;
2286 }
2287 }
2288 }
2289 }
2290
2291 // Now process the command line argument packages, if any. Note that explicitly-
2292 // named system-partition packages will be included even if includeSystem was
2293 // set to false.
2294 if (mPackages != null) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002295 for (String pkgName : mPackages) {
2296 try {
2297 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2298 PackageManager.GET_SIGNATURES));
2299 } catch (NameNotFoundException e) {
2300 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2301 }
2302 }
2303 }
2304
Christopher Tatea858cb02011-06-03 12:27:51 -07002305 // Cull any packages that have indicated that backups are not permitted.
2306 for (int i = 0; i < packagesToBackup.size(); ) {
Christopher Tate240c7d22011-10-03 18:13:44 -07002307 PackageInfo pkg = packagesToBackup.get(i);
2308 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002309 packagesToBackup.remove(i);
2310 } else {
2311 i++;
2312 }
2313 }
2314
Christopher Tate7926a692011-07-11 11:31:57 -07002315 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002316 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002317
Christopher Tate4a627c72011-04-01 14:43:32 -07002318 PackageInfo pkg = null;
2319 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002320 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002321 boolean compressing = COMPRESS_FULL_BACKUPS;
2322 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002323
Christopher Tateeef4ae42011-08-05 13:15:53 -07002324 // Verify that the given password matches the currently-active
2325 // backup password, if any
2326 if (hasBackupPassword()) {
2327 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2328 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2329 return;
2330 }
2331 }
2332
Christopher Tate7bdb0962011-07-13 19:30:21 -07002333 // Write the global file header. All strings are UTF-8 encoded; lines end
2334 // with a '\n' byte. Actual backup data begins immediately following the
2335 // final '\n'.
2336 //
2337 // line 1: "ANDROID BACKUP"
2338 // line 2: backup file format version, currently "1"
2339 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002340 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2341 //
2342 // When line 4 is not "none", then additional header data follows:
2343 //
2344 // line 5: user password salt [hex]
2345 // line 6: master key checksum salt [hex]
2346 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2347 // line 8: IV of the user key [hex]
2348 // line 9: master key blob [hex]
2349 // IV of the master key, master key itself, master key checksum hash
2350 //
2351 // The master key checksum is the master key plus its checksum salt, run through
2352 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2353 // correct password for decrypting the archive: the master key decrypted from
2354 // the archive using the user-supplied password is also run through PBKDF2 in
2355 // this way, and if the result does not match the checksum as stored in the
2356 // archive, then we know that the user-supplied password does not match the
2357 // archive's.
2358 StringBuilder headerbuf = new StringBuilder(1024);
2359
Christopher Tate7bdb0962011-07-13 19:30:21 -07002360 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002361 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2362 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002363
2364 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002365 // Set up the encryption stage if appropriate, and emit the correct header
2366 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002367 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2368 } else {
2369 headerbuf.append("none\n");
2370 }
2371
Christopher Tate7bdb0962011-07-13 19:30:21 -07002372 byte[] header = headerbuf.toString().getBytes("UTF-8");
2373 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002374
2375 // Set up the compression stage feeding into the encryption stage (if any)
2376 if (compressing) {
2377 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2378 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2379 }
2380
2381 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002382 } catch (Exception e) {
2383 // Should never happen!
2384 Slog.e(TAG, "Unable to emit archive header", e);
2385 return;
2386 }
2387
Christopher Tateb0628bf2011-06-02 15:08:13 -07002388 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002389 int N = packagesToBackup.size();
2390 for (int i = 0; i < N; i++) {
2391 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002392 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002393 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002394
Christopher Tate6853fcf2011-08-10 17:52:21 -07002395 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002396 if (mIncludeShared) {
2397 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002398 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002399
2400 // Done!
2401 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002402 } catch (RemoteException e) {
2403 Slog.e(TAG, "App died during full backup");
2404 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002405 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002406 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002407 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002408 mOutputFile.close();
2409 } catch (IOException e) {
2410 /* nothing we can do about this */
2411 }
2412 synchronized (mCurrentOpLock) {
2413 mCurrentOperations.clear();
2414 }
2415 synchronized (mLatchObject) {
2416 mLatchObject.set(true);
2417 mLatchObject.notifyAll();
2418 }
2419 sendEndBackup();
Christopher Tate4a627c72011-04-01 14:43:32 -07002420 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002421 mWakelock.release();
Christopher Tate4a627c72011-04-01 14:43:32 -07002422 }
2423 }
2424
Christopher Tate2efd2db2011-07-19 16:32:49 -07002425 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2426 OutputStream ofstream) throws Exception {
2427 // User key will be used to encrypt the master key.
2428 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002429 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002430 PBKDF2_HASH_ROUNDS);
2431
2432 // the master key is random for each backup
2433 byte[] masterPw = new byte[256 / 8];
2434 mRng.nextBytes(masterPw);
2435 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2436
2437 // primary encryption of the datastream with the random key
2438 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2439 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2440 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2441 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2442
2443 // line 4: name of encryption algorithm
2444 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2445 headerbuf.append('\n');
2446 // line 5: user password salt [hex]
2447 headerbuf.append(byteArrayToHex(newUserSalt));
2448 headerbuf.append('\n');
2449 // line 6: master key checksum salt [hex]
2450 headerbuf.append(byteArrayToHex(checksumSalt));
2451 headerbuf.append('\n');
2452 // line 7: number of PBKDF2 rounds used [decimal]
2453 headerbuf.append(PBKDF2_HASH_ROUNDS);
2454 headerbuf.append('\n');
2455
2456 // line 8: IV of the user key [hex]
2457 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2458 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2459
2460 byte[] IV = mkC.getIV();
2461 headerbuf.append(byteArrayToHex(IV));
2462 headerbuf.append('\n');
2463
2464 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2465 // [byte] IV length = Niv
2466 // [array of Niv bytes] IV itself
2467 // [byte] master key length = Nmk
2468 // [array of Nmk bytes] master key itself
2469 // [byte] MK checksum hash length = Nck
2470 // [array of Nck bytes] master key checksum hash
2471 //
2472 // The checksum is the (master key + checksum salt), run through the
2473 // stated number of PBKDF2 rounds
2474 IV = c.getIV();
2475 byte[] mk = masterKeySpec.getEncoded();
2476 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2477 checksumSalt, PBKDF2_HASH_ROUNDS);
2478
2479 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2480 + checksum.length + 3);
2481 DataOutputStream mkOut = new DataOutputStream(blob);
2482 mkOut.writeByte(IV.length);
2483 mkOut.write(IV);
2484 mkOut.writeByte(mk.length);
2485 mkOut.write(mk);
2486 mkOut.writeByte(checksum.length);
2487 mkOut.write(checksum);
2488 mkOut.flush();
2489 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2490 headerbuf.append(byteArrayToHex(encryptedMk));
2491 headerbuf.append('\n');
2492
2493 return finalOutput;
2494 }
2495
2496 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002497 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002498 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2499
2500 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2501 IApplicationThread.BACKUP_MODE_FULL);
2502 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002503 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002504 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002505 pipes = ParcelFileDescriptor.createPipe();
2506
Christopher Tateb0628bf2011-06-02 15:08:13 -07002507 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002508 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002509 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2510 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2511 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2512
2513 sendOnBackupPackage(pkg.packageName);
2514
Christopher Tate7926a692011-07-11 11:31:57 -07002515 final int token = generateToken();
2516 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2517 token, sendApk);
2518 pipes[1].close(); // the runner has dup'd it
2519 pipes[1] = null;
2520 Thread t = new Thread(runner);
2521 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002522
Christopher Tate7926a692011-07-11 11:31:57 -07002523 // Now pull data from the app and stuff it into the compressor
2524 try {
2525 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2526 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002527
Christopher Tate7926a692011-07-11 11:31:57 -07002528 byte[] buffer = new byte[16 * 1024];
2529 int chunkTotal;
2530 while ((chunkTotal = in.readInt()) > 0) {
2531 while (chunkTotal > 0) {
2532 int toRead = (chunkTotal > buffer.length)
2533 ? buffer.length : chunkTotal;
2534 int nRead = in.read(buffer, 0, toRead);
2535 out.write(buffer, 0, nRead);
2536 chunkTotal -= nRead;
2537 }
2538 }
2539 } catch (IOException e) {
2540 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002541 }
2542
Christopher Tateb0628bf2011-06-02 15:08:13 -07002543 if (!waitUntilOperationComplete(token)) {
2544 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2545 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002546 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002547 }
Christopher Tate7926a692011-07-11 11:31:57 -07002548
Christopher Tateb0628bf2011-06-02 15:08:13 -07002549 } catch (IOException e) {
2550 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002551 } finally {
2552 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002553 // flush after every package
2554 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002555 if (pipes != null) {
2556 if (pipes[0] != null) pipes[0].close();
2557 if (pipes[1] != null) pipes[1].close();
2558 }
Christopher Tate7926a692011-07-11 11:31:57 -07002559 } catch (IOException e) {
2560 Slog.w(TAG, "Error bringing down backup stack");
2561 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002562 }
2563 } else {
2564 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2565 }
2566 tearDown(pkg);
2567 }
2568
Christopher Tate79ec80d2011-06-24 14:58:49 -07002569 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2570 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2571 final String appSourceDir = pkg.applicationInfo.sourceDir;
2572 final String apkDir = new File(appSourceDir).getParent();
2573 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2574 apkDir, appSourceDir, output);
2575
2576 // Save associated .obb content if it exists and we did save the apk
2577 // check for .obb and save those too
2578 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2579 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002580 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002581 File[] obbFiles = obbDir.listFiles();
2582 if (obbFiles != null) {
2583 final String obbDirName = obbDir.getAbsolutePath();
2584 for (File obb : obbFiles) {
2585 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2586 obbDirName, obb.getAbsolutePath(), output);
2587 }
2588 }
2589 }
2590 }
2591
Christopher Tateb0628bf2011-06-02 15:08:13 -07002592 private void backupSharedStorage() throws RemoteException {
2593 PackageInfo pkg = null;
2594 try {
2595 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2596 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2597 IApplicationThread.BACKUP_MODE_FULL);
2598 if (agent != null) {
2599 sendOnBackupPackage("Shared storage");
2600
2601 final int token = generateToken();
Christopher Tate8e294d42011-08-31 20:37:12 -07002602 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL, null);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002603 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002604 if (!waitUntilOperationComplete(token)) {
2605 Slog.e(TAG, "Full backup failed on shared storage");
2606 } else {
2607 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2608 }
2609 } else {
2610 Slog.e(TAG, "Could not bind to shared storage backup agent");
2611 }
2612 } catch (NameNotFoundException e) {
2613 Slog.e(TAG, "Shared storage backup package not found");
2614 } finally {
2615 tearDown(pkg);
2616 }
2617 }
2618
Christopher Tate6853fcf2011-08-10 17:52:21 -07002619 private void finalizeBackup(OutputStream out) {
2620 try {
2621 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2622 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2623 out.write(eof);
2624 } catch (IOException e) {
2625 Slog.w(TAG, "Error attempting to finalize backup stream");
2626 }
2627 }
2628
Christopher Tate4a627c72011-04-01 14:43:32 -07002629 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2630 throws IOException {
2631 // Manifest format. All data are strings ending in LF:
2632 // BACKUP_MANIFEST_VERSION, currently 1
2633 //
2634 // Version 1:
2635 // package name
2636 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002637 // platform versionCode
2638 // getInstallerPackageName() for this package (maybe empty)
2639 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002640 // number of signatures == N
2641 // N*: signature byte array in ascii format per Signature.toCharsString()
2642 StringBuilder builder = new StringBuilder(4096);
2643 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2644
2645 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2646 printer.println(pkg.packageName);
2647 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002648 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2649
2650 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2651 printer.println((installerName != null) ? installerName : "");
2652
Christopher Tate4a627c72011-04-01 14:43:32 -07002653 printer.println(withApk ? "1" : "0");
2654 if (pkg.signatures == null) {
2655 printer.println("0");
2656 } else {
2657 printer.println(Integer.toString(pkg.signatures.length));
2658 for (Signature sig : pkg.signatures) {
2659 printer.println(sig.toCharsString());
2660 }
2661 }
2662
2663 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002664 outstream.write(builder.toString().getBytes());
2665 outstream.close();
2666 }
2667
2668 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002669 if (pkg != null) {
2670 final ApplicationInfo app = pkg.applicationInfo;
2671 if (app != null) {
2672 try {
2673 // unbind and tidy up even on timeout or failure, just in case
2674 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002675
Christopher Tateb0628bf2011-06-02 15:08:13 -07002676 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002677 if (app.uid != Process.SYSTEM_UID
2678 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002679 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002680 mActivityManager.killApplicationProcess(app.processName, app.uid);
2681 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002682 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002683 }
2684 } catch (RemoteException e) {
2685 Slog.d(TAG, "Lost app trying to shut down");
2686 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002687 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002688 }
2689 }
2690
2691 // wrappers for observer use
2692 void sendStartBackup() {
2693 if (mObserver != null) {
2694 try {
2695 mObserver.onStartBackup();
2696 } catch (RemoteException e) {
2697 Slog.w(TAG, "full backup observer went away: startBackup");
2698 mObserver = null;
2699 }
2700 }
2701 }
2702
2703 void sendOnBackupPackage(String name) {
2704 if (mObserver != null) {
2705 try {
2706 // TODO: use a more user-friendly name string
2707 mObserver.onBackupPackage(name);
2708 } catch (RemoteException e) {
2709 Slog.w(TAG, "full backup observer went away: backupPackage");
2710 mObserver = null;
2711 }
2712 }
2713 }
2714
2715 void sendEndBackup() {
2716 if (mObserver != null) {
2717 try {
2718 mObserver.onEndBackup();
2719 } catch (RemoteException e) {
2720 Slog.w(TAG, "full backup observer went away: endBackup");
2721 mObserver = null;
2722 }
2723 }
2724 }
2725 }
2726
2727
Christopher Tate75a99702011-05-18 16:28:19 -07002728 // ----- Full restore from a file/socket -----
2729
2730 // Description of a file in the restore datastream
2731 static class FileMetadata {
2732 String packageName; // name of the owning app
2733 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002734 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002735 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2736 String path; // subpath within the semantic domain
2737 long mode; // e.g. 0666 (actually int)
2738 long mtime; // last mod time, UTC time_t (actually int)
2739 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002740
2741 @Override
2742 public String toString() {
2743 StringBuilder sb = new StringBuilder(128);
2744 sb.append("FileMetadata{");
2745 sb.append(packageName); sb.append(',');
2746 sb.append(type); sb.append(',');
2747 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2748 sb.append(size);
2749 sb.append('}');
2750 return sb.toString();
2751 }
Christopher Tate75a99702011-05-18 16:28:19 -07002752 }
2753
2754 enum RestorePolicy {
2755 IGNORE,
2756 ACCEPT,
2757 ACCEPT_IF_APK
2758 }
2759
2760 class PerformFullRestoreTask implements Runnable {
2761 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002762 String mCurrentPassword;
2763 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002764 IFullBackupRestoreObserver mObserver;
2765 AtomicBoolean mLatchObject;
2766 IBackupAgent mAgent;
2767 String mAgentPackage;
2768 ApplicationInfo mTargetApp;
2769 ParcelFileDescriptor[] mPipes = null;
2770
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002771 long mBytes;
2772
Christopher Tate75a99702011-05-18 16:28:19 -07002773 // possible handling states for a given package in the restore dataset
2774 final HashMap<String, RestorePolicy> mPackagePolicies
2775 = new HashMap<String, RestorePolicy>();
2776
2777 // installer package names for each encountered app, derived from the manifests
2778 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2779
2780 // Signatures for a given package found in its manifest file
2781 final HashMap<String, Signature[]> mManifestSignatures
2782 = new HashMap<String, Signature[]>();
2783
2784 // Packages we've already wiped data on when restoring their first file
2785 final HashSet<String> mClearedPackages = new HashSet<String>();
2786
Christopher Tate728a1c42011-07-28 18:03:03 -07002787 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002788 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002789 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002790 mCurrentPassword = curPassword;
2791 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002792 mObserver = observer;
2793 mLatchObject = latch;
2794 mAgent = null;
2795 mAgentPackage = null;
2796 mTargetApp = null;
2797
2798 // Which packages we've already wiped data on. We prepopulate this
2799 // with a whitelist of packages known to be unclearable.
2800 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002801 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002802
Christopher Tate75a99702011-05-18 16:28:19 -07002803 }
2804
2805 class RestoreFileRunnable implements Runnable {
2806 IBackupAgent mAgent;
2807 FileMetadata mInfo;
2808 ParcelFileDescriptor mSocket;
2809 int mToken;
2810
2811 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2812 ParcelFileDescriptor socket, int token) throws IOException {
2813 mAgent = agent;
2814 mInfo = info;
2815 mToken = token;
2816
2817 // This class is used strictly for process-local binder invocations. The
2818 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2819 // do not automatically get a 'dup'ed descriptor that we can can continue
2820 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2821 // before proceeding to do the restore.
2822 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2823 }
2824
2825 @Override
2826 public void run() {
2827 try {
2828 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2829 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2830 mToken, mBackupManagerBinder);
2831 } catch (RemoteException e) {
2832 // never happens; this is used strictly for local binder calls
2833 }
2834 }
2835 }
2836
2837 @Override
2838 public void run() {
2839 Slog.i(TAG, "--- Performing full-dataset restore ---");
2840 sendStartRestore();
2841
Christopher Tateb0628bf2011-06-02 15:08:13 -07002842 // Are we able to restore shared-storage data?
2843 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2844 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2845 }
2846
Christopher Tate2efd2db2011-07-19 16:32:49 -07002847 FileInputStream rawInStream = null;
2848 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002849 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002850 if (hasBackupPassword()) {
2851 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2852 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2853 return;
2854 }
2855 }
2856
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002857 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002858 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002859 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2860 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002861
2862 // First, parse out the unencrypted/uncompressed header
2863 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002864 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002865 final InputStream in;
2866
2867 boolean okay = false;
2868 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2869 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002870 rawDataIn.readFully(streamHeader);
2871 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2872 if (Arrays.equals(magicBytes, streamHeader)) {
2873 // okay, header looks good. now parse out the rest of the fields.
2874 String s = readHeaderLine(rawInStream);
2875 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2876 // okay, it's a version we recognize
2877 s = readHeaderLine(rawInStream);
2878 compressed = (Integer.parseInt(s) != 0);
2879 s = readHeaderLine(rawInStream);
2880 if (s.equals("none")) {
2881 // no more header to parse; we're good to go
2882 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002883 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002884 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2885 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002886 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002887 }
2888 } else Slog.w(TAG, "Archive is encrypted but no password given");
2889 } else Slog.w(TAG, "Wrong header version: " + s);
2890 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002891
2892 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002893 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002894 return;
2895 }
2896
2897 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002898 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002899
2900 boolean didRestore;
2901 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002902 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002903 } while (didRestore);
2904
Christopher Tatec58efa62011-08-01 19:20:14 -07002905 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002906 } catch (IOException e) {
2907 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002908 } finally {
2909 tearDownPipes();
2910 tearDownAgent(mTargetApp);
2911
2912 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002913 if (rawDataIn != null) rawDataIn.close();
2914 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002915 mInputFile.close();
2916 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002917 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002918 /* nothing we can do about this */
2919 }
2920 synchronized (mCurrentOpLock) {
2921 mCurrentOperations.clear();
2922 }
2923 synchronized (mLatchObject) {
2924 mLatchObject.set(true);
2925 mLatchObject.notifyAll();
2926 }
2927 sendEndRestore();
Christopher Tatec58efa62011-08-01 19:20:14 -07002928 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate336a6492011-10-05 16:05:43 -07002929 mWakelock.release();
Christopher Tate75a99702011-05-18 16:28:19 -07002930 }
2931 }
2932
Christopher Tate7bdb0962011-07-13 19:30:21 -07002933 String readHeaderLine(InputStream in) throws IOException {
2934 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002935 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002936 while ((c = in.read()) >= 0) {
2937 if (c == '\n') break; // consume and discard the newlines
2938 buffer.append((char)c);
2939 }
2940 return buffer.toString();
2941 }
2942
Christopher Tate2efd2db2011-07-19 16:32:49 -07002943 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2944 InputStream result = null;
2945 try {
2946 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2947
2948 String userSaltHex = readHeaderLine(rawInStream); // 5
2949 byte[] userSalt = hexToByteArray(userSaltHex);
2950
2951 String ckSaltHex = readHeaderLine(rawInStream); // 6
2952 byte[] ckSalt = hexToByteArray(ckSaltHex);
2953
2954 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2955 String userIvHex = readHeaderLine(rawInStream); // 8
2956
2957 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2958
2959 // decrypt the master key blob
2960 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002961 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002962 rounds);
2963 byte[] IV = hexToByteArray(userIvHex);
2964 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2965 c.init(Cipher.DECRYPT_MODE,
2966 new SecretKeySpec(userKey.getEncoded(), "AES"),
2967 ivSpec);
2968 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2969 byte[] mkBlob = c.doFinal(mkCipher);
2970
2971 // first, the master key IV
2972 int offset = 0;
2973 int len = mkBlob[offset++];
2974 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2975 offset += len;
2976 // then the master key itself
2977 len = mkBlob[offset++];
2978 byte[] mk = Arrays.copyOfRange(mkBlob,
2979 offset, offset + len);
2980 offset += len;
2981 // and finally the master key checksum hash
2982 len = mkBlob[offset++];
2983 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2984 offset, offset + len);
2985
2986 // now validate the decrypted master key against the checksum
2987 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2988 if (Arrays.equals(calculatedCk, mkChecksum)) {
2989 ivSpec = new IvParameterSpec(IV);
2990 c.init(Cipher.DECRYPT_MODE,
2991 new SecretKeySpec(mk, "AES"),
2992 ivSpec);
2993 // Only if all of the above worked properly will 'result' be assigned
2994 result = new CipherInputStream(rawInStream, c);
2995 } else Slog.w(TAG, "Incorrect password");
2996 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2997 } catch (InvalidAlgorithmParameterException e) {
2998 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2999 } catch (BadPaddingException e) {
3000 // This case frequently occurs when the wrong password is used to decrypt
3001 // the master key. Use the identical "incorrect password" log text as is
3002 // used in the checksum failure log in order to avoid providing additional
3003 // information to an attacker.
3004 Slog.w(TAG, "Incorrect password");
3005 } catch (IllegalBlockSizeException e) {
3006 Slog.w(TAG, "Invalid block size in master key");
3007 } catch (NoSuchAlgorithmException e) {
3008 Slog.e(TAG, "Needed decryption algorithm unavailable!");
3009 } catch (NoSuchPaddingException e) {
3010 Slog.e(TAG, "Needed padding mechanism unavailable!");
3011 } catch (InvalidKeyException e) {
3012 Slog.w(TAG, "Illegal password; aborting");
3013 } catch (NumberFormatException e) {
3014 Slog.w(TAG, "Can't parse restore data header");
3015 } catch (IOException e) {
3016 Slog.w(TAG, "Can't read input header");
3017 }
3018
3019 return result;
3020 }
3021
Christopher Tate75a99702011-05-18 16:28:19 -07003022 boolean restoreOneFile(InputStream instream, byte[] buffer) {
3023 FileMetadata info;
3024 try {
3025 info = readTarHeaders(instream);
3026 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07003027 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07003028 dumpFileMetadata(info);
3029 }
3030
3031 final String pkg = info.packageName;
3032 if (!pkg.equals(mAgentPackage)) {
3033 // okay, change in package; set up our various
3034 // bookkeeping if we haven't seen it yet
3035 if (!mPackagePolicies.containsKey(pkg)) {
3036 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3037 }
3038
3039 // Clean up the previous agent relationship if necessary,
3040 // and let the observer know we're considering a new app.
3041 if (mAgent != null) {
3042 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3043 tearDownPipes();
3044 tearDownAgent(mTargetApp);
3045 mTargetApp = null;
3046 mAgentPackage = null;
3047 }
3048 }
3049
3050 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3051 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3052 mPackageInstallers.put(pkg, info.installerPackageName);
3053 // We've read only the manifest content itself at this point,
3054 // so consume the footer before looping around to the next
3055 // input file
3056 skipTarPadding(info.size, instream);
3057 sendOnRestorePackage(pkg);
3058 } else {
3059 // Non-manifest, so it's actual file data. Is this a package
3060 // we're ignoring?
3061 boolean okay = true;
3062 RestorePolicy policy = mPackagePolicies.get(pkg);
3063 switch (policy) {
3064 case IGNORE:
3065 okay = false;
3066 break;
3067
3068 case ACCEPT_IF_APK:
3069 // If we're in accept-if-apk state, then the first file we
3070 // see MUST be the apk.
3071 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3072 if (DEBUG) Slog.d(TAG, "APK file; installing");
3073 // Try to install the app.
3074 String installerName = mPackageInstallers.get(pkg);
3075 okay = installApk(info, installerName, instream);
3076 // good to go; promote to ACCEPT
3077 mPackagePolicies.put(pkg, (okay)
3078 ? RestorePolicy.ACCEPT
3079 : RestorePolicy.IGNORE);
3080 // At this point we've consumed this file entry
3081 // ourselves, so just strip the tar footer and
3082 // go on to the next file in the input stream
3083 skipTarPadding(info.size, instream);
3084 return true;
3085 } else {
3086 // File data before (or without) the apk. We can't
3087 // handle it coherently in this case so ignore it.
3088 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3089 okay = false;
3090 }
3091 break;
3092
3093 case ACCEPT:
3094 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3095 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3096 // we can take the data without the apk, so we
3097 // *want* to do so. skip the apk by declaring this
3098 // one file not-okay without changing the restore
3099 // policy for the package.
3100 okay = false;
3101 }
3102 break;
3103
3104 default:
3105 // Something has gone dreadfully wrong when determining
3106 // the restore policy from the manifest. Ignore the
3107 // rest of this package's data.
3108 Slog.e(TAG, "Invalid policy from manifest");
3109 okay = false;
3110 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3111 break;
3112 }
3113
3114 // If the policy is satisfied, go ahead and set up to pipe the
3115 // data to the agent.
3116 if (DEBUG && okay && mAgent != null) {
3117 Slog.i(TAG, "Reusing existing agent instance");
3118 }
3119 if (okay && mAgent == null) {
3120 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3121
3122 try {
3123 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3124
3125 // If we haven't sent any data to this app yet, we probably
3126 // need to clear it first. Check that.
3127 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003128 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003129 // responsible for coherently managing a full
3130 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003131 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003132 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3133 clearApplicationDataSynchronous(pkg);
3134 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003135 if (DEBUG) Slog.d(TAG, "backup agent ("
3136 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003137 }
3138 mClearedPackages.add(pkg);
3139 } else {
3140 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3141 }
3142
3143 // All set; now set up the IPC and launch the agent
3144 setUpPipes();
3145 mAgent = bindToAgentSynchronous(mTargetApp,
3146 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3147 mAgentPackage = pkg;
3148 } catch (IOException e) {
3149 // fall through to error handling
3150 } catch (NameNotFoundException e) {
3151 // fall through to error handling
3152 }
3153
3154 if (mAgent == null) {
3155 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3156 okay = false;
3157 tearDownPipes();
3158 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3159 }
3160 }
3161
3162 // Sanity check: make sure we never give data to the wrong app. This
3163 // should never happen but a little paranoia here won't go amiss.
3164 if (okay && !pkg.equals(mAgentPackage)) {
3165 Slog.e(TAG, "Restoring data for " + pkg
3166 + " but agent is for " + mAgentPackage);
3167 okay = false;
3168 }
3169
3170 // At this point we have an agent ready to handle the full
3171 // restore data as well as a pipe for sending data to
3172 // that agent. Tell the agent to start reading from the
3173 // pipe.
3174 if (okay) {
3175 boolean agentSuccess = true;
3176 long toCopy = info.size;
3177 final int token = generateToken();
3178 try {
3179 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3180 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003181 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003182 // fire up the app's agent listening on the socket. If
3183 // the agent is running in the system process we can't
3184 // just invoke it asynchronously, so we provide a thread
3185 // for it here.
3186 if (mTargetApp.processName.equals("system")) {
3187 Slog.d(TAG, "system process agent - spinning a thread");
3188 RestoreFileRunnable runner = new RestoreFileRunnable(
3189 mAgent, info, mPipes[0], token);
3190 new Thread(runner).start();
3191 } else {
3192 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3193 info.domain, info.path, info.mode, info.mtime,
3194 token, mBackupManagerBinder);
3195 }
3196 } catch (IOException e) {
3197 // couldn't dup the socket for a process-local restore
3198 Slog.d(TAG, "Couldn't establish restore");
3199 agentSuccess = false;
3200 okay = false;
3201 } catch (RemoteException e) {
3202 // whoops, remote agent went away. We'll eat the content
3203 // ourselves, then, and not copy it over.
3204 Slog.e(TAG, "Agent crashed during full restore");
3205 agentSuccess = false;
3206 okay = false;
3207 }
3208
3209 // Copy over the data if the agent is still good
3210 if (okay) {
3211 boolean pipeOkay = true;
3212 FileOutputStream pipe = new FileOutputStream(
3213 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003214 while (toCopy > 0) {
3215 int toRead = (toCopy > buffer.length)
3216 ? buffer.length : (int)toCopy;
3217 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003218 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003219 if (nRead <= 0) break;
3220 toCopy -= nRead;
3221
3222 // send it to the output pipe as long as things
3223 // are still good
3224 if (pipeOkay) {
3225 try {
3226 pipe.write(buffer, 0, nRead);
3227 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003228 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003229 pipeOkay = false;
3230 }
3231 }
3232 }
3233
3234 // done sending that file! Now we just need to consume
3235 // the delta from info.size to the end of block.
3236 skipTarPadding(info.size, instream);
3237
3238 // and now that we've sent it all, wait for the remote
3239 // side to acknowledge receipt
3240 agentSuccess = waitUntilOperationComplete(token);
3241 }
3242
3243 // okay, if the remote end failed at any point, deal with
3244 // it by ignoring the rest of the restore on it
3245 if (!agentSuccess) {
3246 mBackupHandler.removeMessages(MSG_TIMEOUT);
3247 tearDownPipes();
3248 tearDownAgent(mTargetApp);
3249 mAgent = null;
3250 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3251 }
3252 }
3253
3254 // Problems setting up the agent communication, or an already-
3255 // ignored package: skip to the next tar stream entry by
3256 // reading and discarding this file.
3257 if (!okay) {
3258 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3259 long bytesToConsume = (info.size + 511) & ~511;
3260 while (bytesToConsume > 0) {
3261 int toRead = (bytesToConsume > buffer.length)
3262 ? buffer.length : (int)bytesToConsume;
3263 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003264 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003265 if (nRead <= 0) break;
3266 bytesToConsume -= nRead;
3267 }
3268 }
3269 }
3270 }
3271 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003272 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003273 // treat as EOF
3274 info = null;
3275 }
3276
3277 return (info != null);
3278 }
3279
3280 void setUpPipes() throws IOException {
3281 mPipes = ParcelFileDescriptor.createPipe();
3282 }
3283
3284 void tearDownPipes() {
3285 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003286 try {
3287 mPipes[0].close();
3288 mPipes[0] = null;
3289 mPipes[1].close();
3290 mPipes[1] = null;
3291 } catch (IOException e) {
3292 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003293 }
3294 mPipes = null;
3295 }
3296 }
3297
3298 void tearDownAgent(ApplicationInfo app) {
3299 if (mAgent != null) {
3300 try {
3301 // unbind and tidy up even on timeout or failure, just in case
3302 mActivityManager.unbindBackupAgent(app);
3303
3304 // The agent was running with a stub Application object, so shut it down.
3305 // !!! We hardcode the confirmation UI's package name here rather than use a
3306 // manifest flag! TODO something less direct.
3307 if (app.uid != Process.SYSTEM_UID
3308 && !app.packageName.equals("com.android.backupconfirm")) {
3309 if (DEBUG) Slog.d(TAG, "Killing host process");
3310 mActivityManager.killApplicationProcess(app.processName, app.uid);
3311 } else {
3312 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3313 }
3314 } catch (RemoteException e) {
3315 Slog.d(TAG, "Lost app trying to shut down");
3316 }
3317 mAgent = null;
3318 }
3319 }
3320
3321 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3322 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003323 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003324 int mResult;
3325
3326 public void reset() {
3327 synchronized (mDone) {
3328 mDone.set(false);
3329 }
3330 }
3331
3332 public void waitForCompletion() {
3333 synchronized (mDone) {
3334 while (mDone.get() == false) {
3335 try {
3336 mDone.wait();
3337 } catch (InterruptedException e) { }
3338 }
3339 }
3340 }
3341
3342 int getResult() {
3343 return mResult;
3344 }
3345
3346 @Override
3347 public void packageInstalled(String packageName, int returnCode)
3348 throws RemoteException {
3349 synchronized (mDone) {
3350 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003351 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003352 mDone.set(true);
3353 mDone.notifyAll();
3354 }
3355 }
3356 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003357
3358 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3359 final AtomicBoolean mDone = new AtomicBoolean();
3360 int mResult;
3361
3362 public void reset() {
3363 synchronized (mDone) {
3364 mDone.set(false);
3365 }
3366 }
3367
3368 public void waitForCompletion() {
3369 synchronized (mDone) {
3370 while (mDone.get() == false) {
3371 try {
3372 mDone.wait();
3373 } catch (InterruptedException e) { }
3374 }
3375 }
3376 }
3377
3378 @Override
3379 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3380 synchronized (mDone) {
3381 mResult = returnCode;
3382 mDone.set(true);
3383 mDone.notifyAll();
3384 }
3385 }
3386 }
3387
Christopher Tate75a99702011-05-18 16:28:19 -07003388 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003389 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003390
3391 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3392 boolean okay = true;
3393
3394 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3395
3396 // The file content is an .apk file. Copy it out to a staging location and
3397 // attempt to install it.
3398 File apkFile = new File(mDataDir, info.packageName);
3399 try {
3400 FileOutputStream apkStream = new FileOutputStream(apkFile);
3401 byte[] buffer = new byte[32 * 1024];
3402 long size = info.size;
3403 while (size > 0) {
3404 long toRead = (buffer.length < size) ? buffer.length : size;
3405 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003406 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003407 apkStream.write(buffer, 0, didRead);
3408 size -= didRead;
3409 }
3410 apkStream.close();
3411
3412 // make sure the installer can read it
3413 apkFile.setReadable(true, false);
3414
3415 // Now install it
3416 Uri packageUri = Uri.fromFile(apkFile);
3417 mInstallObserver.reset();
3418 mPackageManager.installPackage(packageUri, mInstallObserver,
Christopher Tateab63aa82011-09-26 16:30:30 -07003419 PackageManager.INSTALL_REPLACE_EXISTING | PackageManager.INSTALL_FROM_ADB,
3420 installerPackage);
Christopher Tate75a99702011-05-18 16:28:19 -07003421 mInstallObserver.waitForCompletion();
3422
3423 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3424 // The only time we continue to accept install of data even if the
3425 // apk install failed is if we had already determined that we could
3426 // accept the data regardless.
3427 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3428 okay = false;
3429 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003430 } else {
3431 // Okay, the install succeeded. Make sure it was the right app.
3432 boolean uninstall = false;
3433 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3434 Slog.w(TAG, "Restore stream claimed to include apk for "
3435 + info.packageName + " but apk was really "
3436 + mInstallObserver.mPackageName);
3437 // delete the package we just put in place; it might be fraudulent
3438 okay = false;
3439 uninstall = true;
3440 } else {
3441 try {
3442 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3443 PackageManager.GET_SIGNATURES);
3444 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3445 Slog.w(TAG, "Restore stream contains apk of package "
3446 + info.packageName + " but it disallows backup/restore");
3447 okay = false;
3448 } else {
3449 // So far so good -- do the signatures match the manifest?
3450 Signature[] sigs = mManifestSignatures.get(info.packageName);
3451 if (!signaturesMatch(sigs, pkg)) {
3452 Slog.w(TAG, "Installed app " + info.packageName
3453 + " signatures do not match restore manifest");
3454 okay = false;
3455 uninstall = true;
3456 }
3457 }
3458 } catch (NameNotFoundException e) {
3459 Slog.w(TAG, "Install of package " + info.packageName
3460 + " succeeded but now not found");
3461 okay = false;
3462 }
3463 }
3464
3465 // If we're not okay at this point, we need to delete the package
3466 // that we just installed.
3467 if (uninstall) {
3468 mDeleteObserver.reset();
3469 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3470 mDeleteObserver, 0);
3471 mDeleteObserver.waitForCompletion();
3472 }
Christopher Tate75a99702011-05-18 16:28:19 -07003473 }
3474 } catch (IOException e) {
3475 Slog.e(TAG, "Unable to transcribe restored apk for install");
3476 okay = false;
3477 } finally {
3478 apkFile.delete();
3479 }
3480
3481 return okay;
3482 }
3483
3484 // Given an actual file content size, consume the post-content padding mandated
3485 // by the tar format.
3486 void skipTarPadding(long size, InputStream instream) throws IOException {
3487 long partial = (size + 512) % 512;
3488 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003489 final int needed = 512 - (int)partial;
3490 byte[] buffer = new byte[needed];
3491 if (readExactly(instream, buffer, 0, needed) == needed) {
3492 mBytes += needed;
3493 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003494 }
3495 }
3496
3497 // Returns a policy constant; takes a buffer arg to reduce memory churn
3498 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3499 throws IOException {
3500 // Fail on suspiciously large manifest files
3501 if (info.size > 64 * 1024) {
3502 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3503 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003504
Christopher Tate75a99702011-05-18 16:28:19 -07003505 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003506 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3507 mBytes += info.size;
3508 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003509
3510 RestorePolicy policy = RestorePolicy.IGNORE;
3511 String[] str = new String[1];
3512 int offset = 0;
3513
3514 try {
3515 offset = extractLine(buffer, offset, str);
3516 int version = Integer.parseInt(str[0]);
3517 if (version == BACKUP_MANIFEST_VERSION) {
3518 offset = extractLine(buffer, offset, str);
3519 String manifestPackage = str[0];
3520 // TODO: handle <original-package>
3521 if (manifestPackage.equals(info.packageName)) {
3522 offset = extractLine(buffer, offset, str);
3523 version = Integer.parseInt(str[0]); // app version
3524 offset = extractLine(buffer, offset, str);
3525 int platformVersion = Integer.parseInt(str[0]);
3526 offset = extractLine(buffer, offset, str);
3527 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3528 offset = extractLine(buffer, offset, str);
3529 boolean hasApk = str[0].equals("1");
3530 offset = extractLine(buffer, offset, str);
3531 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003532 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003533 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003534 for (int i = 0; i < numSigs; i++) {
3535 offset = extractLine(buffer, offset, str);
3536 sigs[i] = new Signature(str[0]);
3537 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003538 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003539
3540 // Okay, got the manifest info we need...
3541 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003542 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3543 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003544 // Fall through to IGNORE if the app explicitly disallows backup
3545 final int flags = pkgInfo.applicationInfo.flags;
3546 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3547 // Verify signatures against any installed version; if they
3548 // don't match, then we fall though and ignore the data. The
3549 // signatureMatch() method explicitly ignores the signature
3550 // check for packages installed on the system partition, because
3551 // such packages are signed with the platform cert instead of
3552 // the app developer's cert, so they're different on every
3553 // device.
3554 if (signaturesMatch(sigs, pkgInfo)) {
3555 if (pkgInfo.versionCode >= version) {
3556 Slog.i(TAG, "Sig + version match; taking data");
3557 policy = RestorePolicy.ACCEPT;
3558 } else {
3559 // The data is from a newer version of the app than
3560 // is presently installed. That means we can only
3561 // use it if the matching apk is also supplied.
3562 Slog.d(TAG, "Data version " + version
3563 + " is newer than installed version "
3564 + pkgInfo.versionCode + " - requiring apk");
3565 policy = RestorePolicy.ACCEPT_IF_APK;
3566 }
Christopher Tate75a99702011-05-18 16:28:19 -07003567 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003568 Slog.w(TAG, "Restore manifest signatures do not match "
3569 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003570 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003571 } else {
3572 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3573 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003574 }
3575 } catch (NameNotFoundException e) {
3576 // Okay, the target app isn't installed. We can process
3577 // the restore properly only if the dataset provides the
3578 // apk file and we can successfully install it.
3579 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3580 + " not installed; requiring apk in dataset");
3581 policy = RestorePolicy.ACCEPT_IF_APK;
3582 }
3583
3584 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3585 Slog.i(TAG, "Cannot restore package " + info.packageName
3586 + " without the matching .apk");
3587 }
3588 } else {
3589 Slog.i(TAG, "Missing signature on backed-up package "
3590 + info.packageName);
3591 }
3592 } else {
3593 Slog.i(TAG, "Expected package " + info.packageName
3594 + " but restore manifest claims " + manifestPackage);
3595 }
3596 } else {
3597 Slog.i(TAG, "Unknown restore manifest version " + version
3598 + " for package " + info.packageName);
3599 }
3600 } catch (NumberFormatException e) {
3601 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003602 } catch (IllegalArgumentException e) {
3603 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003604 }
3605
3606 return policy;
3607 }
3608
3609 // Builds a line from a byte buffer starting at 'offset', and returns
3610 // the index of the next unconsumed data in the buffer.
3611 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3612 final int end = buffer.length;
3613 if (offset >= end) throw new IOException("Incomplete data");
3614
3615 int pos;
3616 for (pos = offset; pos < end; pos++) {
3617 byte c = buffer[pos];
3618 // at LF we declare end of line, and return the next char as the
3619 // starting point for the next time through
3620 if (c == '\n') {
3621 break;
3622 }
3623 }
3624 outStr[0] = new String(buffer, offset, pos - offset);
3625 pos++; // may be pointing an extra byte past the end but that's okay
3626 return pos;
3627 }
3628
3629 void dumpFileMetadata(FileMetadata info) {
3630 if (DEBUG) {
3631 StringBuilder b = new StringBuilder(128);
3632
3633 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003634 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003635 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3636 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3637 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3638 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3639 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3640 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3641 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3642 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3643 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3644 b.append(String.format(" %9d ", info.size));
3645
3646 Date stamp = new Date(info.mtime);
3647 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3648
3649 b.append(info.packageName);
3650 b.append(" :: ");
3651 b.append(info.domain);
3652 b.append(" :: ");
3653 b.append(info.path);
3654
3655 Slog.i(TAG, b.toString());
3656 }
3657 }
3658 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3659 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3660 byte[] block = new byte[512];
3661 FileMetadata info = null;
3662
3663 boolean gotHeader = readTarHeader(instream, block);
3664 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003665 try {
3666 // okay, presume we're okay, and extract the various metadata
3667 info = new FileMetadata();
3668 info.size = extractRadix(block, 124, 12, 8);
3669 info.mtime = extractRadix(block, 136, 12, 8);
3670 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003671
Christopher Tate2efd2db2011-07-19 16:32:49 -07003672 info.path = extractString(block, 345, 155); // prefix
3673 String path = extractString(block, 0, 100);
3674 if (path.length() > 0) {
3675 if (info.path.length() > 0) info.path += '/';
3676 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003677 }
Christopher Tate75a99702011-05-18 16:28:19 -07003678
Christopher Tate2efd2db2011-07-19 16:32:49 -07003679 // tar link indicator field: 1 byte at offset 156 in the header.
3680 int typeChar = block[156];
3681 if (typeChar == 'x') {
3682 // pax extended header, so we need to read that
3683 gotHeader = readPaxExtendedHeader(instream, info);
3684 if (gotHeader) {
3685 // and after a pax extended header comes another real header -- read
3686 // that to find the real file type
3687 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003688 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003689 if (!gotHeader) throw new IOException("Bad or missing pax header");
3690
3691 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003692 }
Christopher Tate75a99702011-05-18 16:28:19 -07003693
Christopher Tate2efd2db2011-07-19 16:32:49 -07003694 switch (typeChar) {
3695 case '0': info.type = BackupAgent.TYPE_FILE; break;
3696 case '5': {
3697 info.type = BackupAgent.TYPE_DIRECTORY;
3698 if (info.size != 0) {
3699 Slog.w(TAG, "Directory entry with nonzero size in header");
3700 info.size = 0;
3701 }
3702 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003703 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003704 case 0: {
3705 // presume EOF
3706 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3707 return null;
3708 }
3709 default: {
3710 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3711 throw new IOException("Unknown entity type " + typeChar);
3712 }
Christopher Tate75a99702011-05-18 16:28:19 -07003713 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003714
3715 // Parse out the path
3716 //
3717 // first: apps/shared/unrecognized
3718 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3719 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3720 // File in shared storage. !!! TODO: implement this.
3721 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3722 info.packageName = "com.android.sharedstoragebackup";
3723 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3724 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3725 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3726 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3727 // App content! Parse out the package name and domain
3728
3729 // strip the apps/ prefix
3730 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3731
3732 // extract the package name
3733 int slash = info.path.indexOf('/');
3734 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3735 info.packageName = info.path.substring(0, slash);
3736 info.path = info.path.substring(slash+1);
3737
3738 // if it's a manifest we're done, otherwise parse out the domains
3739 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3740 slash = info.path.indexOf('/');
3741 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3742 info.domain = info.path.substring(0, slash);
3743 // validate that it's one of the domains we understand
3744 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3745 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3746 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3747 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3748 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3749 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3750 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3751 throw new IOException("Unrecognized domain " + info.domain);
3752 }
3753
3754 info.path = info.path.substring(slash + 1);
3755 }
3756 }
3757 } catch (IOException e) {
3758 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003759 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003760 HEXLOG(block);
3761 }
3762 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003763 }
3764 }
3765 return info;
3766 }
3767
Christopher Tate2efd2db2011-07-19 16:32:49 -07003768 private void HEXLOG(byte[] block) {
3769 int offset = 0;
3770 int todo = block.length;
3771 StringBuilder buf = new StringBuilder(64);
3772 while (todo > 0) {
3773 buf.append(String.format("%04x ", offset));
3774 int numThisLine = (todo > 16) ? 16 : todo;
3775 for (int i = 0; i < numThisLine; i++) {
3776 buf.append(String.format("%02x ", block[offset+i]));
3777 }
3778 Slog.i("hexdump", buf.toString());
3779 buf.setLength(0);
3780 todo -= numThisLine;
3781 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003782 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003783 }
3784
Christopher Tate6853fcf2011-08-10 17:52:21 -07003785 // Read exactly the given number of bytes into a buffer at the stated offset.
3786 // Returns false if EOF is encountered before the requested number of bytes
3787 // could be read.
3788 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3789 throws IOException {
3790 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3791
3792 int soFar = 0;
3793 while (soFar < size) {
3794 int nRead = in.read(buffer, offset + soFar, size - soFar);
3795 if (nRead <= 0) {
3796 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3797 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003798 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003799 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003800 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003801 return soFar;
3802 }
3803
3804 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3805 final int got = readExactly(instream, block, 0, 512);
3806 if (got == 0) return false; // Clean EOF
3807 if (got < 512) throw new IOException("Unable to read full block header");
3808 mBytes += 512;
3809 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003810 }
3811
3812 // overwrites 'info' fields based on the pax extended header
3813 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3814 throws IOException {
3815 // We should never see a pax extended header larger than this
3816 if (info.size > 32*1024) {
3817 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3818 + " - aborting");
3819 throw new IOException("Sanity failure: pax header size " + info.size);
3820 }
3821
3822 // read whole blocks, not just the content size
3823 int numBlocks = (int)((info.size + 511) >> 9);
3824 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003825 if (readExactly(instream, data, 0, data.length) < data.length) {
3826 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003827 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003828 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003829
3830 final int contentSize = (int) info.size;
3831 int offset = 0;
3832 do {
3833 // extract the line at 'offset'
3834 int eol = offset+1;
3835 while (eol < contentSize && data[eol] != ' ') eol++;
3836 if (eol >= contentSize) {
3837 // error: we just hit EOD looking for the end of the size field
3838 throw new IOException("Invalid pax data");
3839 }
3840 // eol points to the space between the count and the key
3841 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3842 int key = eol + 1; // start of key=value
3843 eol = offset + linelen - 1; // trailing LF
3844 int value;
3845 for (value = key+1; data[value] != '=' && value <= eol; value++);
3846 if (value > eol) {
3847 throw new IOException("Invalid pax declaration");
3848 }
3849
3850 // pax requires that key/value strings be in UTF-8
3851 String keyStr = new String(data, key, value-key, "UTF-8");
3852 // -1 to strip the trailing LF
3853 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3854
3855 if ("path".equals(keyStr)) {
3856 info.path = valStr;
3857 } else if ("size".equals(keyStr)) {
3858 info.size = Long.parseLong(valStr);
3859 } else {
3860 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3861 }
3862
3863 offset += linelen;
3864 } while (offset < contentSize);
3865
3866 return true;
3867 }
3868
3869 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3870 throws IOException {
3871 long value = 0;
3872 final int end = offset + maxChars;
3873 for (int i = offset; i < end; i++) {
3874 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003875 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003876 if (b == 0 || b == ' ') break;
3877 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003878 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003879 }
3880 value = radix * value + (b - '0');
3881 }
3882 return value;
3883 }
3884
3885 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3886 final int end = offset + maxChars;
3887 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003888 // tar string fields terminate early with a NUL
3889 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003890 return new String(data, offset, eos-offset, "US-ASCII");
3891 }
3892
3893 void sendStartRestore() {
3894 if (mObserver != null) {
3895 try {
3896 mObserver.onStartRestore();
3897 } catch (RemoteException e) {
3898 Slog.w(TAG, "full restore observer went away: startRestore");
3899 mObserver = null;
3900 }
3901 }
3902 }
3903
3904 void sendOnRestorePackage(String name) {
3905 if (mObserver != null) {
3906 try {
3907 // TODO: use a more user-friendly name string
3908 mObserver.onRestorePackage(name);
3909 } catch (RemoteException e) {
3910 Slog.w(TAG, "full restore observer went away: restorePackage");
3911 mObserver = null;
3912 }
3913 }
3914 }
3915
3916 void sendEndRestore() {
3917 if (mObserver != null) {
3918 try {
3919 mObserver.onEndRestore();
3920 } catch (RemoteException e) {
3921 Slog.w(TAG, "full restore observer went away: endRestore");
3922 mObserver = null;
3923 }
3924 }
3925 }
3926 }
3927
Christopher Tatedf01dea2009-06-09 20:45:02 -07003928 // ----- Restore handling -----
3929
Christopher Tate78dd4a72009-11-04 11:49:08 -08003930 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3931 // If the target resides on the system partition, we allow it to restore
3932 // data from the like-named package in a restore set even if the signatures
3933 // do not match. (Unlike general applications, those flashed to the system
3934 // partition will be signed with the device's platform certificate, so on
3935 // different phones the same system app will have different signatures.)
3936 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003937 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003938 return true;
3939 }
3940
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003941 // Allow unsigned apps, but not signed on one device and unsigned on the other
3942 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003943 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003944 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003945 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003946 if ((storedSigs == null || storedSigs.length == 0)
3947 && (deviceSigs == null || deviceSigs.length == 0)) {
3948 return true;
3949 }
3950 if (storedSigs == null || deviceSigs == null) {
3951 return false;
3952 }
3953
Christopher Tateabce4e82009-06-18 18:35:32 -07003954 // !!! TODO: this demands that every stored signature match one
3955 // that is present on device, and does not demand the converse.
3956 // Is this this right policy?
3957 int nStored = storedSigs.length;
3958 int nDevice = deviceSigs.length;
3959
3960 for (int i=0; i < nStored; i++) {
3961 boolean match = false;
3962 for (int j=0; j < nDevice; j++) {
3963 if (storedSigs[i].equals(deviceSigs[j])) {
3964 match = true;
3965 break;
3966 }
3967 }
3968 if (!match) {
3969 return false;
3970 }
3971 }
3972 return true;
3973 }
3974
Christopher Tate2982d062011-09-06 20:35:24 -07003975 enum RestoreState {
3976 INITIAL,
3977 DOWNLOAD_DATA,
3978 PM_METADATA,
3979 RUNNING_QUEUE,
3980 FINAL
3981 }
3982
3983 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003984 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003985 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003986 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003987 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003988 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003989 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003990 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003991 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07003992 private long mStartRealtime;
3993 private PackageManagerBackupAgent mPmAgent;
3994 private List<PackageInfo> mAgentPackages;
3995 private ArrayList<PackageInfo> mRestorePackages;
3996 private RestoreState mCurrentState;
3997 private int mCount;
3998 private boolean mFinished;
3999 private int mStatus;
4000 private File mBackupDataName;
4001 private File mNewStateName;
4002 private File mSavedStateName;
4003 private ParcelFileDescriptor mBackupData;
4004 private ParcelFileDescriptor mNewState;
4005 private PackageInfo mCurrentPackage;
4006
Christopher Tatedf01dea2009-06-09 20:45:02 -07004007
Christopher Tate5cbbf562009-06-22 16:44:51 -07004008 class RestoreRequest {
4009 public PackageInfo app;
4010 public int storedAppVersion;
4011
4012 RestoreRequest(PackageInfo _app, int _version) {
4013 app = _app;
4014 storedAppVersion = _version;
4015 }
4016 }
4017
Christopher Tate44a27902010-01-27 17:15:49 -08004018 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07004019 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07004020 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07004021 mCurrentState = RestoreState.INITIAL;
4022 mFinished = false;
4023 mPmAgent = null;
4024
Christopher Tatedf01dea2009-06-09 20:45:02 -07004025 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004026 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004027 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08004028 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08004029 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07004030 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07004031
Christopher Tate284f1bb2011-07-07 14:31:18 -07004032 if (filterSet != null) {
4033 mFilterSet = new HashSet<String>();
4034 for (String pkg : filterSet) {
4035 mFilterSet.add(pkg);
4036 }
4037 } else {
4038 mFilterSet = null;
4039 }
4040
Christopher Tate5cb400b2009-06-25 16:03:14 -07004041 try {
4042 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4043 } catch (RemoteException e) {
4044 // can't happen; the transport is local
4045 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004046 }
4047
Christopher Tate2982d062011-09-06 20:35:24 -07004048 // Execute one tick of whatever state machine the task implements
4049 @Override
4050 public void execute() {
4051 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4052 switch (mCurrentState) {
4053 case INITIAL:
4054 beginRestore();
4055 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004056
Christopher Tate2982d062011-09-06 20:35:24 -07004057 case DOWNLOAD_DATA:
4058 downloadRestoreData();
4059 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004060
Christopher Tate2982d062011-09-06 20:35:24 -07004061 case PM_METADATA:
4062 restorePmMetadata();
4063 break;
4064
4065 case RUNNING_QUEUE:
4066 restoreNextAgent();
4067 break;
4068
4069 case FINAL:
4070 if (!mFinished) finalizeRestore();
4071 else {
4072 Slog.e(TAG, "Duplicate finish");
4073 }
4074 mFinished = true;
4075 break;
4076 }
4077 }
4078
4079 // Initialize and set up for the PM metadata restore, which comes first
4080 void beginRestore() {
4081 // Don't account time doing the restore as inactivity of the app
4082 // that has opened a restore session.
4083 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4084
4085 // Assume error until we successfully init everything
4086 mStatus = BackupConstants.TRANSPORT_ERROR;
4087
Christopher Tatedf01dea2009-06-09 20:45:02 -07004088 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004089 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004090 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004091
Dan Egnorefe52642009-06-24 00:16:33 -07004092 // Get the list of all packages which have backup enabled.
4093 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004094 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004095 PackageInfo omPackage = new PackageInfo();
4096 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004097 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004098
Christopher Tate2982d062011-09-06 20:35:24 -07004099 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004100 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004101 // if there's a filter set, strip out anything that isn't
4102 // present before proceeding
4103 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004104 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4105 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004106 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004107 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004108 }
4109 }
Christopher Tate2982d062011-09-06 20:35:24 -07004110 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004111 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004112 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004113 Slog.i(TAG, " " + p);
4114 }
4115 }
4116 }
Christopher Tate2982d062011-09-06 20:35:24 -07004117 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004118 } else {
4119 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004120 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004121 }
Dan Egnorefe52642009-06-24 00:16:33 -07004122
Christopher Tate7d562ec2009-06-25 18:03:43 -07004123 // let the observer know that we're running
4124 if (mObserver != null) {
4125 try {
4126 // !!! TODO: get an actual count from the transport after
4127 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004128 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004129 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004130 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004131 mObserver = null;
4132 }
4133 }
Christopher Tate2982d062011-09-06 20:35:24 -07004134 } catch (RemoteException e) {
4135 // Something has gone catastrophically wrong with the transport
4136 Slog.e(TAG, "Error communicating with transport for restore");
4137 executeNextState(RestoreState.FINAL);
4138 return;
4139 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004140
Christopher Tate2982d062011-09-06 20:35:24 -07004141 mStatus = BackupConstants.TRANSPORT_OK;
4142 executeNextState(RestoreState.DOWNLOAD_DATA);
4143 }
4144
4145 void downloadRestoreData() {
4146 // Note that the download phase can be very time consuming, but we're executing
4147 // it inline here on the looper. This is "okay" because it is not calling out to
4148 // third party code; the transport is "trusted," and so we assume it is being a
4149 // good citizen and timing out etc when appropriate.
4150 //
4151 // TODO: when appropriate, move the download off the looper and rearrange the
4152 // error handling around that.
4153 try {
4154 mStatus = mTransport.startRestore(mToken,
4155 mRestorePackages.toArray(new PackageInfo[0]));
4156 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004157 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004158 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004159 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004160 return;
4161 }
Christopher Tate2982d062011-09-06 20:35:24 -07004162 } catch (RemoteException e) {
4163 Slog.e(TAG, "Error communicating with transport for restore");
4164 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4165 mStatus = BackupConstants.TRANSPORT_ERROR;
4166 executeNextState(RestoreState.FINAL);
4167 return;
4168 }
Dan Egnorefe52642009-06-24 00:16:33 -07004169
Christopher Tate2982d062011-09-06 20:35:24 -07004170 // Successful download of the data to be parceled out to the apps, so off we go.
4171 executeNextState(RestoreState.PM_METADATA);
4172 }
4173
4174 void restorePmMetadata() {
4175 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004176 String packageName = mTransport.nextRestorePackage();
4177 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004178 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004179 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004180 mStatus = BackupConstants.TRANSPORT_ERROR;
4181 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004182 return;
4183 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004184 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004185 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004186 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004187 mStatus = BackupConstants.TRANSPORT_OK;
4188 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004189 return;
4190 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004191 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004192 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004193 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004194 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004195 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004196 return;
4197 }
4198
4199 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004200 PackageInfo omPackage = new PackageInfo();
4201 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4202 mPmAgent = new PackageManagerBackupAgent(
4203 mPackageManager, mAgentPackages);
4204 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004205 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004206 // The PM agent called operationComplete() already, because our invocation
4207 // of it is process-local and therefore synchronous. That means that a
4208 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4209 // proceed with running the queue do we remove that pending message and
4210 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004211
Christopher Tate8c032472009-07-02 14:28:47 -07004212 // Verify that the backup set includes metadata. If not, we can't do
4213 // signature/version verification etc, so we simply do not proceed with
4214 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004215 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004216 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004217 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004218 "Package manager restore metadata missing");
4219 mStatus = BackupConstants.TRANSPORT_ERROR;
4220 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4221 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004222 return;
4223 }
Christopher Tate2982d062011-09-06 20:35:24 -07004224 } catch (RemoteException e) {
4225 Slog.e(TAG, "Error communicating with transport for restore");
4226 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4227 mStatus = BackupConstants.TRANSPORT_ERROR;
4228 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4229 executeNextState(RestoreState.FINAL);
4230 return;
4231 }
Christopher Tate8c032472009-07-02 14:28:47 -07004232
Christopher Tate2982d062011-09-06 20:35:24 -07004233 // Metadata is intact, so we can now run the restore queue. If we get here,
4234 // we have already enqueued the necessary next-step message on the looper.
4235 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004236
Christopher Tate2982d062011-09-06 20:35:24 -07004237 void restoreNextAgent() {
4238 try {
4239 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004240
Christopher Tate2982d062011-09-06 20:35:24 -07004241 if (packageName == null) {
4242 Slog.e(TAG, "Error getting next restore package");
4243 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4244 executeNextState(RestoreState.FINAL);
4245 return;
4246 } else if (packageName.equals("")) {
4247 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4248 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4249 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4250 executeNextState(RestoreState.FINAL);
4251 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004252 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004253
4254 if (mObserver != null) {
4255 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004256 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004257 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004258 Slog.d(TAG, "Restore observer died in onUpdate");
4259 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004260 }
4261 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004262
Christopher Tate2982d062011-09-06 20:35:24 -07004263 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4264 if (metaInfo == null) {
4265 Slog.e(TAG, "Missing metadata for " + packageName);
4266 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4267 "Package metadata missing");
4268 executeNextState(RestoreState.RUNNING_QUEUE);
4269 return;
Christopher Tate84725812010-02-04 15:52:40 -08004270 }
4271
Christopher Tate2982d062011-09-06 20:35:24 -07004272 PackageInfo packageInfo;
4273 try {
4274 int flags = PackageManager.GET_SIGNATURES;
4275 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4276 } catch (NameNotFoundException e) {
4277 Slog.e(TAG, "Invalid package restoring data", e);
4278 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4279 "Package missing on device");
4280 executeNextState(RestoreState.RUNNING_QUEUE);
4281 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004282 }
4283
Christopher Tate2982d062011-09-06 20:35:24 -07004284 if (metaInfo.versionCode > packageInfo.versionCode) {
4285 // Data is from a "newer" version of the app than we have currently
4286 // installed. If the app has not declared that it is prepared to
4287 // handle this case, we do not attempt the restore.
4288 if ((packageInfo.applicationInfo.flags
4289 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4290 String message = "Version " + metaInfo.versionCode
4291 + " > installed version " + packageInfo.versionCode;
4292 Slog.w(TAG, "Package " + packageName + ": " + message);
4293 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4294 packageName, message);
4295 executeNextState(RestoreState.RUNNING_QUEUE);
4296 return;
4297 } else {
4298 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4299 + " > installed " + packageInfo.versionCode
4300 + " but restoreAnyVersion");
4301 }
4302 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004303
Christopher Tate2982d062011-09-06 20:35:24 -07004304 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4305 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4306 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4307 "Signature mismatch");
4308 executeNextState(RestoreState.RUNNING_QUEUE);
4309 return;
4310 }
4311
4312 if (DEBUG) Slog.v(TAG, "Package " + packageName
4313 + " restore version [" + metaInfo.versionCode
4314 + "] is compatible with installed version ["
4315 + packageInfo.versionCode + "]");
4316
4317 // Then set up and bind the agent
4318 IBackupAgent agent = bindToAgentSynchronous(
4319 packageInfo.applicationInfo,
4320 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4321 if (agent == null) {
4322 Slog.w(TAG, "Can't find backup agent for " + packageName);
4323 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4324 "Restore agent missing");
4325 executeNextState(RestoreState.RUNNING_QUEUE);
4326 return;
4327 }
4328
4329 // And then finally start the restore on this agent
4330 try {
4331 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4332 ++mCount;
4333 } catch (Exception e) {
4334 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4335 agentErrorCleanup();
4336 executeNextState(RestoreState.RUNNING_QUEUE);
4337 }
4338 } catch (RemoteException e) {
4339 Slog.e(TAG, "Unable to fetch restore data from transport");
4340 mStatus = BackupConstants.TRANSPORT_ERROR;
4341 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004342 }
4343 }
4344
Christopher Tate2982d062011-09-06 20:35:24 -07004345 void finalizeRestore() {
4346 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4347
4348 try {
4349 mTransport.finishRestore();
4350 } catch (RemoteException e) {
4351 Slog.e(TAG, "Error finishing restore", e);
4352 }
4353
4354 if (mObserver != null) {
4355 try {
4356 mObserver.restoreFinished(mStatus);
4357 } catch (RemoteException e) {
4358 Slog.d(TAG, "Restore observer died at restoreFinished");
4359 }
4360 }
4361
4362 // If this was a restoreAll operation, record that this was our
4363 // ancestral dataset, as well as the set of apps that are possibly
4364 // restoreable from the dataset
4365 if (mTargetPackage == null && mPmAgent != null) {
4366 mAncestralPackages = mPmAgent.getRestoredPackages();
4367 mAncestralToken = mToken;
4368 writeRestoreTokens();
4369 }
4370
4371 // We must under all circumstances tell the Package Manager to
4372 // proceed with install notifications if it's waiting for us.
4373 if (mPmToken > 0) {
4374 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4375 try {
4376 mPackageManagerBinder.finishPackageInstall(mPmToken);
4377 } catch (RemoteException e) { /* can't happen */ }
4378 }
4379
4380 // Furthermore we need to reset the session timeout clock
4381 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4382 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4383 TIMEOUT_RESTORE_INTERVAL);
4384
4385 // done; we can finally release the wakelock
4386 Slog.i(TAG, "Restore complete.");
4387 mWakelock.release();
4388 }
4389
4390 // Call asynchronously into the app, passing it the restore data. The next step
4391 // after this is always a callback, either operationComplete() or handleTimeout().
4392 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004393 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004394 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004395 final String packageName = app.packageName;
4396
Christopher Tate2982d062011-09-06 20:35:24 -07004397 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004398
Christopher Tatec7b31e32009-06-10 15:49:30 -07004399 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004400 mBackupDataName = new File(mDataDir, packageName + ".restore");
4401 mNewStateName = new File(mStateDir, packageName + ".new");
4402 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004403
Christopher Tate4a627c72011-04-01 14:43:32 -07004404 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004405 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004406 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004407 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004408 ParcelFileDescriptor.MODE_READ_WRITE |
4409 ParcelFileDescriptor.MODE_CREATE |
4410 ParcelFileDescriptor.MODE_TRUNCATE);
4411
Christopher Tate2982d062011-09-06 20:35:24 -07004412 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Christopher Tate5f2f4132011-09-26 13:10:38 -07004413 // Transport-level failure, so we wind everything up and
4414 // terminate the restore operation.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004415 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004416 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate5f2f4132011-09-26 13:10:38 -07004417 mBackupData.close();
4418 mBackupDataName.delete();
4419 executeNextState(RestoreState.FINAL);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004420 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004421 }
4422
4423 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004424 mBackupData.close();
4425 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004426 ParcelFileDescriptor.MODE_READ_ONLY);
4427
Christopher Tate2982d062011-09-06 20:35:24 -07004428 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004429 ParcelFileDescriptor.MODE_READ_WRITE |
4430 ParcelFileDescriptor.MODE_CREATE |
4431 ParcelFileDescriptor.MODE_TRUNCATE);
4432
Christopher Tate44a27902010-01-27 17:15:49 -08004433 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004434 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4435 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004436 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004437 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004438 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004439 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004440
Christopher Tate2982d062011-09-06 20:35:24 -07004441 // After a restore failure we go back to running the queue. If there
4442 // are no more packages to be restored that will be handled by the
4443 // next step.
4444 executeNextState(RestoreState.RUNNING_QUEUE);
4445 }
4446 }
Chris Tate249345b2010-10-29 12:57:04 -07004447
Christopher Tate2982d062011-09-06 20:35:24 -07004448 void agentErrorCleanup() {
4449 // If the agent fails restore, it might have put the app's data
4450 // into an incoherent state. For consistency we wipe its data
4451 // again in this case before continuing with normal teardown
4452 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4453 agentCleanup();
4454 }
4455
4456 void agentCleanup() {
4457 mBackupDataName.delete();
4458 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4459 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4460 mBackupData = mNewState = null;
4461
4462 // if everything went okay, remember the recorded state now
4463 //
4464 // !!! TODO: the restored data should be migrated on the server
4465 // side into the current dataset. In that case the new state file
4466 // we just created would reflect the data already extant in the
4467 // backend, so there'd be nothing more to do. Until that happens,
4468 // however, we need to make sure that we record the data to the
4469 // current backend dataset. (Yes, this means shipping the data over
4470 // the wire in both directions. That's bad, but consistency comes
4471 // first, then efficiency.) Once we introduce server-side data
4472 // migration to the newly-restored device's dataset, we will change
4473 // the following from a discard of the newly-written state to the
4474 // "correct" operation of renaming into the canonical state blob.
4475 mNewStateName.delete(); // TODO: remove; see above comment
4476 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4477
4478 // If this wasn't the PM pseudopackage, tear down the agent side
4479 if (mCurrentPackage.applicationInfo != null) {
4480 // unbind and tidy up even on timeout or failure
4481 try {
4482 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4483
4484 // The agent was probably running with a stub Application object,
4485 // which isn't a valid run mode for the main app logic. Shut
4486 // down the app so that next time it's launched, it gets the
4487 // usual full initialization. Note that this is only done for
4488 // full-system restores: when a single app has requested a restore,
4489 // it is explicitly not killed following that operation.
4490 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4491 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4492 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4493 + mCurrentPackage.applicationInfo.processName);
4494 mActivityManager.killApplicationProcess(
4495 mCurrentPackage.applicationInfo.processName,
4496 mCurrentPackage.applicationInfo.uid);
4497 }
4498 } catch (RemoteException e) {
4499 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004500 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004501 }
Christopher Tate2982d062011-09-06 20:35:24 -07004502
4503 // The caller is responsible for reestablishing the state machine; our
4504 // responsibility here is to clear the decks for whatever comes next.
4505 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4506 synchronized (mCurrentOpLock) {
4507 mCurrentOperations.clear();
4508 }
4509 }
4510
4511 // A call to agent.doRestore() has been positively acknowledged as complete
4512 @Override
4513 public void operationComplete() {
4514 int size = (int) mBackupDataName.length();
4515 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4516 // Just go back to running the restore queue
4517 agentCleanup();
4518
4519 executeNextState(RestoreState.RUNNING_QUEUE);
4520 }
4521
4522 // A call to agent.doRestore() has timed out
4523 @Override
4524 public void handleTimeout() {
4525 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4526 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4527 mCurrentPackage.packageName, "restore timeout");
4528 // Handle like an agent that threw on invocation: wipe it and go on to the next
4529 agentErrorCleanup();
4530 executeNextState(RestoreState.RUNNING_QUEUE);
4531 }
4532
4533 void executeNextState(RestoreState nextState) {
4534 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4535 + this + " nextState=" + nextState);
4536 mCurrentState = nextState;
4537 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4538 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004539 }
4540 }
4541
Christopher Tate44a27902010-01-27 17:15:49 -08004542 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004543 IBackupTransport mTransport;
4544 PackageInfo mPackage;
4545
Christopher Tate44a27902010-01-27 17:15:49 -08004546 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004547 mTransport = transport;
4548 mPackage = packageInfo;
4549 }
4550
Christopher Tateee0e78a2009-07-02 11:17:03 -07004551 public void run() {
4552 try {
4553 // Clear the on-device backup state to ensure a full backup next time
4554 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4555 File stateFile = new File(stateDir, mPackage.packageName);
4556 stateFile.delete();
4557
4558 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004559 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004560 mTransport.clearBackupData(mPackage);
4561 } catch (RemoteException e) {
4562 // can't happen; the transport is local
4563 } finally {
4564 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004565 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004566 mTransport.finishBackup();
4567 } catch (RemoteException e) {
4568 // can't happen; the transport is local
4569 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004570
4571 // Last but not least, release the cpu
4572 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004573 }
4574 }
4575 }
4576
Christopher Tate44a27902010-01-27 17:15:49 -08004577 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004578 HashSet<String> mQueue;
4579
Christopher Tate44a27902010-01-27 17:15:49 -08004580 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004581 mQueue = transportNames;
4582 }
4583
Christopher Tate4cc86e12009-09-21 19:36:51 -07004584 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004585 try {
4586 for (String transportName : mQueue) {
4587 IBackupTransport transport = getTransport(transportName);
4588 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004589 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004590 continue;
4591 }
4592
Joe Onorato8a9b2202010-02-26 18:56:32 -08004593 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004594 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004595 long startRealtime = SystemClock.elapsedRealtime();
4596 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004597
Christopher Tate4cc86e12009-09-21 19:36:51 -07004598 if (status == BackupConstants.TRANSPORT_OK) {
4599 status = transport.finishBackup();
4600 }
4601
4602 // Okay, the wipe really happened. Clean up our local bookkeeping.
4603 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004604 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004605 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004606 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004607 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004608 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004609 synchronized (mQueueLock) {
4610 recordInitPendingLocked(false, transportName);
4611 }
Dan Egnor726247c2009-09-29 19:12:31 -07004612 } else {
4613 // If this didn't work, requeue this one and try again
4614 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004615 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004616 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004617 synchronized (mQueueLock) {
4618 recordInitPendingLocked(true, transportName);
4619 }
4620 // do this via another alarm to make sure of the wakelock states
4621 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004622 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004623 + transportName + " resched in " + delay);
4624 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4625 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004626 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004627 }
4628 } catch (RemoteException e) {
4629 // can't happen; the transports are local
4630 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004631 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004632 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004633 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004634 mWakelock.release();
4635 }
4636 }
4637 }
4638
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004639 private void dataChangedImpl(String packageName) {
4640 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4641 dataChangedImpl(packageName, targets);
4642 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004643
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004644 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004645 // Record that we need a backup pass for the caller. Since multiple callers
4646 // may share a uid, we need to note all candidates within that uid and schedule
4647 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004648 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004649
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004650 if (targets == null) {
4651 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4652 + " uid=" + Binder.getCallingUid());
4653 return;
4654 }
4655
4656 synchronized (mQueueLock) {
4657 // Note that this client has made data changes that need to be backed up
4658 for (ApplicationInfo app : targets) {
4659 // validate the caller-supplied package name against the known set of
4660 // packages associated with this uid
4661 if (app.packageName.equals(packageName)) {
4662 // Add the caller to the set of pending backups. If there is
4663 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004664 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004665 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004666 // Journal this request in case of crash. The put()
4667 // operation returned null when this package was not already
4668 // in the set; we want to avoid touching the disk redundantly.
4669 writeToJournalLocked(packageName);
4670
Christopher Tatec58efa62011-08-01 19:20:14 -07004671 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004672 int numKeys = mPendingBackups.size();
4673 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4674 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004675 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004676 }
4677 }
4678 }
4679 }
4680 }
4681 }
4682 }
4683
4684 // Note: packageName is currently unused, but may be in the future
4685 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004686 // If the caller does not hold the BACKUP permission, it can only request a
4687 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004688 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004689 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004690 synchronized (mBackupParticipants) {
4691 return mBackupParticipants.get(Binder.getCallingUid());
4692 }
4693 }
4694
4695 // a caller with full permission can ask to back up any participating app
4696 // !!! TODO: allow backup of ANY app?
4697 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4698 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004699 int N = mBackupParticipants.size();
4700 for (int i = 0; i < N; i++) {
4701 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4702 if (s != null) {
4703 targets.addAll(s);
4704 }
4705 }
4706 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004707 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004708 }
Christopher Tate46758122009-05-06 11:22:00 -07004709
Christopher Tatecde87f42009-06-12 12:55:53 -07004710 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004711 RandomAccessFile out = null;
4712 try {
4713 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4714 out = new RandomAccessFile(mJournal, "rws");
4715 out.seek(out.length());
4716 out.writeUTF(str);
4717 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004718 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004719 mJournal = null;
4720 } finally {
4721 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004722 }
4723 }
4724
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004725 // ----- IBackupManager binder interface -----
4726
4727 public void dataChanged(final String packageName) {
4728 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4729 if (targets == null) {
4730 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4731 + " uid=" + Binder.getCallingUid());
4732 return;
4733 }
4734
4735 mBackupHandler.post(new Runnable() {
4736 public void run() {
4737 dataChangedImpl(packageName, targets);
4738 }
4739 });
4740 }
4741
Christopher Tateee0e78a2009-07-02 11:17:03 -07004742 // Clear the given package's backup data from the current transport
4743 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004744 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004745 PackageInfo info;
4746 try {
4747 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4748 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004749 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004750 return;
4751 }
4752
4753 // If the caller does not hold the BACKUP permission, it can only request a
4754 // wipe of its own backed-up data.
4755 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004756 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004757 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4758 apps = mBackupParticipants.get(Binder.getCallingUid());
4759 } else {
4760 // a caller with full permission can ask to back up any participating app
4761 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004762 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004763 apps = new HashSet<ApplicationInfo>();
4764 int N = mBackupParticipants.size();
4765 for (int i = 0; i < N; i++) {
4766 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4767 if (s != null) {
4768 apps.addAll(s);
4769 }
4770 }
4771 }
4772
4773 // now find the given package in the set of candidate apps
4774 for (ApplicationInfo app : apps) {
4775 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004776 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004777 // found it; fire off the clear request
4778 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004779 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004780 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004781 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4782 new ClearParams(getTransport(mCurrentTransport), info));
4783 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004784 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004785 }
4786 break;
4787 }
4788 }
4789 }
4790
Christopher Tateace7f092009-06-15 18:07:25 -07004791 // Run a backup pass immediately for any applications that have declared
4792 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004793 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004795
Joe Onorato8a9b2202010-02-26 18:56:32 -08004796 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004797 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004798 // Because the alarms we are using can jitter, and we want an *immediate*
4799 // backup pass to happen, we restart the timer beginning with "next time,"
4800 // then manually fire the backup trigger intent ourselves.
4801 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004802 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004803 mRunBackupIntent.send();
4804 } catch (PendingIntent.CanceledException e) {
4805 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004806 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004807 }
Christopher Tate46758122009-05-06 11:22:00 -07004808 }
4809 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004810
Christopher Tated2c0cd42011-09-15 15:51:29 -07004811 boolean deviceIsProvisioned() {
4812 final ContentResolver resolver = mContext.getContentResolver();
4813 return (Settings.Secure.getInt(resolver, Settings.Secure.DEVICE_PROVISIONED, 0) != 0);
4814 }
4815
Christopher Tate4a627c72011-04-01 14:43:32 -07004816 // Run a *full* backup pass for the given package, writing the resulting data stream
4817 // to the supplied file descriptor. This method is synchronous and does not return
4818 // to the caller until the backup has been completed.
4819 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004820 boolean doAllApps, boolean includeSystem, String[] pkgList) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004821 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4822
4823 // Validate
4824 if (!doAllApps) {
4825 if (!includeShared) {
4826 // If we're backing up shared data (sdcard or equivalent), then we can run
4827 // without any supplied app names. Otherwise, we'd be doing no work, so
4828 // report the error.
4829 if (pkgList == null || pkgList.length == 0) {
4830 throw new IllegalArgumentException(
4831 "Backup requested but neither shared nor any apps named");
4832 }
4833 }
4834 }
4835
Christopher Tate4a627c72011-04-01 14:43:32 -07004836 long oldId = Binder.clearCallingIdentity();
4837 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004838 // Doesn't make sense to do a full backup prior to setup
4839 if (!deviceIsProvisioned()) {
4840 Slog.i(TAG, "Full backup not supported before setup");
4841 return;
4842 }
4843
4844 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4845 + " shared=" + includeShared + " all=" + doAllApps
4846 + " pkgs=" + pkgList);
4847 Slog.i(TAG, "Beginning full backup...");
4848
Christopher Tate4a627c72011-04-01 14:43:32 -07004849 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
Christopher Tate240c7d22011-10-03 18:13:44 -07004850 doAllApps, includeSystem, pkgList);
Christopher Tate4a627c72011-04-01 14:43:32 -07004851 final int token = generateToken();
4852 synchronized (mFullConfirmations) {
4853 mFullConfirmations.put(token, params);
4854 }
4855
Christopher Tate75a99702011-05-18 16:28:19 -07004856 // start up the confirmation UI
4857 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4858 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4859 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004860 mFullConfirmations.delete(token);
4861 return;
4862 }
Christopher Tate75a99702011-05-18 16:28:19 -07004863
4864 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004865 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4866
4867 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004868 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004869
4870 // wait for the backup to be performed
4871 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4872 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004873 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004874 try {
4875 fd.close();
4876 } catch (IOException e) {
4877 // just eat it
4878 }
Christopher Tate75a99702011-05-18 16:28:19 -07004879 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004880 Slog.d(TAG, "Full backup processing complete.");
Christopher Tate4a627c72011-04-01 14:43:32 -07004881 }
Christopher Tate75a99702011-05-18 16:28:19 -07004882 }
4883
4884 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004885 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004886
4887 long oldId = Binder.clearCallingIdentity();
4888
4889 try {
Christopher Tated2c0cd42011-09-15 15:51:29 -07004890 // Check whether the device has been provisioned -- we don't handle
4891 // full restores prior to completing the setup process.
4892 if (!deviceIsProvisioned()) {
4893 Slog.i(TAG, "Full restore not permitted before setup");
4894 return;
4895 }
4896
4897 Slog.i(TAG, "Beginning full restore...");
4898
Christopher Tate75a99702011-05-18 16:28:19 -07004899 FullRestoreParams params = new FullRestoreParams(fd);
4900 final int token = generateToken();
4901 synchronized (mFullConfirmations) {
4902 mFullConfirmations.put(token, params);
4903 }
4904
4905 // start up the confirmation UI
4906 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4907 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4908 Slog.e(TAG, "Unable to launch full restore confirmation");
4909 mFullConfirmations.delete(token);
4910 return;
4911 }
4912
4913 // make sure the screen is lit for the user interaction
4914 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4915
4916 // start the confirmation countdown
4917 startConfirmationTimeout(token, params);
4918
4919 // wait for the restore to be performed
4920 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4921 waitForCompletion(params);
4922 } finally {
4923 try {
4924 fd.close();
4925 } catch (IOException e) {
4926 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4927 }
4928 Binder.restoreCallingIdentity(oldId);
Christopher Tated2c0cd42011-09-15 15:51:29 -07004929 Slog.i(TAG, "Full restore processing complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07004930 }
4931 }
4932
4933 boolean startConfirmationUi(int token, String action) {
4934 try {
4935 Intent confIntent = new Intent(action);
4936 confIntent.setClassName("com.android.backupconfirm",
4937 "com.android.backupconfirm.BackupRestoreConfirmation");
4938 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4939 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4940 mContext.startActivity(confIntent);
4941 } catch (ActivityNotFoundException e) {
4942 return false;
4943 }
4944 return true;
4945 }
4946
4947 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004948 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004949 + TIMEOUT_FULL_CONFIRMATION + " millis");
4950 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4951 token, 0, params);
4952 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004953 }
4954
4955 void waitForCompletion(FullParams params) {
4956 synchronized (params.latch) {
4957 while (params.latch.get() == false) {
4958 try {
4959 params.latch.wait();
4960 } catch (InterruptedException e) { /* never interrupted */ }
4961 }
4962 }
4963 }
4964
4965 void signalFullBackupRestoreCompletion(FullParams params) {
4966 synchronized (params.latch) {
4967 params.latch.set(true);
4968 params.latch.notifyAll();
4969 }
4970 }
4971
4972 // Confirm that the previously-requested full backup/restore operation can proceed. This
4973 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004974 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004975 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004976 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004977 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4978 + " allow=" + allow);
4979
4980 // TODO: possibly require not just this signature-only permission, but even
4981 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004982 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004983
4984 long oldId = Binder.clearCallingIdentity();
4985 try {
4986
4987 FullParams params;
4988 synchronized (mFullConfirmations) {
4989 params = mFullConfirmations.get(token);
4990 if (params != null) {
4991 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4992 mFullConfirmations.delete(token);
4993
4994 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004995 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004996 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004997 : MSG_RUN_FULL_RESTORE;
4998
Christopher Tate728a1c42011-07-28 18:03:03 -07004999 params.observer = observer;
5000 params.curPassword = curPassword;
5001 params.encryptPassword = encPpassword;
5002
Christopher Tate75a99702011-05-18 16:28:19 -07005003 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07005004 mWakelock.acquire();
5005 Message msg = mBackupHandler.obtainMessage(verb, params);
5006 mBackupHandler.sendMessage(msg);
5007 } else {
5008 Slog.w(TAG, "User rejected full backup/restore operation");
5009 // indicate completion without having actually transferred any data
5010 signalFullBackupRestoreCompletion(params);
5011 }
5012 } else {
5013 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
5014 }
5015 }
5016 } finally {
5017 Binder.restoreCallingIdentity(oldId);
5018 }
5019 }
5020
Christopher Tate8031a3d2009-07-06 16:36:05 -07005021 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07005022 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005023 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005024 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005025
Joe Onorato8a9b2202010-02-26 18:56:32 -08005026 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005027
Christopher Tate6ef58a12009-06-29 14:56:28 -07005028 boolean wasEnabled = mEnabled;
5029 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07005030 Settings.Secure.putInt(mContext.getContentResolver(),
5031 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07005032 mEnabled = enable;
5033 }
5034
Christopher Tate49401dd2009-07-01 12:34:29 -07005035 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005036 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07005037 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07005038 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07005039 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07005040 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005041 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07005042
Christopher Tateb6787f22009-07-02 17:40:45 -07005043 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07005044
5045 // This also constitutes an opt-out, so we wipe any data for
5046 // this device from the backend. We start that process with
5047 // an alarm in order to guarantee wakelock states.
5048 if (wasEnabled && mProvisioned) {
5049 // NOTE: we currently flush every registered transport, not just
5050 // the currently-active one.
5051 HashSet<String> allTransports;
5052 synchronized (mTransports) {
5053 allTransports = new HashSet<String>(mTransports.keySet());
5054 }
5055 // build the set of transports for which we are posting an init
5056 for (String transport : allTransports) {
5057 recordInitPendingLocked(true, transport);
5058 }
5059 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
5060 mRunInitIntent);
5061 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005062 }
5063 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005064 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005065
Christopher Tatecce9da52010-02-03 15:11:15 -08005066 // Enable/disable automatic restore of app data at install time
5067 public void setAutoRestore(boolean doAutoRestore) {
5068 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005069 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005070
Joe Onorato8a9b2202010-02-26 18:56:32 -08005071 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005072
5073 synchronized (this) {
5074 Settings.Secure.putInt(mContext.getContentResolver(),
5075 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5076 mAutoRestore = doAutoRestore;
5077 }
5078 }
5079
Christopher Tate8031a3d2009-07-06 16:36:05 -07005080 // Mark the backup service as having been provisioned
5081 public void setBackupProvisioned(boolean available) {
5082 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5083 "setBackupProvisioned");
5084
5085 boolean wasProvisioned = mProvisioned;
5086 synchronized (this) {
5087 Settings.Secure.putInt(mContext.getContentResolver(),
5088 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
5089 mProvisioned = available;
5090 }
5091
5092 synchronized (mQueueLock) {
5093 if (available && !wasProvisioned && mEnabled) {
5094 // we're now good to go, so start the backup alarms
5095 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
5096 } else if (!available) {
5097 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005098 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07005099 mAlarmManager.cancel(mRunBackupIntent);
5100 }
5101 }
5102 }
5103
5104 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005105 // We used to use setInexactRepeating(), but that may be linked to
5106 // backups running at :00 more often than not, creating load spikes.
5107 // Schedule at an exact time for now, and also add a bit of "fuzz".
5108
5109 Random random = new Random();
5110 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5111 random.nextInt(FUZZ_MILLIS);
5112 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5113 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005114 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005115 }
5116
Christopher Tate6ef58a12009-06-29 14:56:28 -07005117 // Report whether the backup mechanism is currently enabled
5118 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005119 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005120 return mEnabled; // no need to synchronize just to read it
5121 }
5122
Christopher Tate91717492009-06-26 21:07:13 -07005123 // Report the name of the currently active transport
5124 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005125 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005126 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005127 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005128 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005129 }
5130
Christopher Tate91717492009-06-26 21:07:13 -07005131 // Report all known, available backup transports
5132 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005133 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005134
Christopher Tate91717492009-06-26 21:07:13 -07005135 String[] list = null;
5136 ArrayList<String> known = new ArrayList<String>();
5137 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5138 if (entry.getValue() != null) {
5139 known.add(entry.getKey());
5140 }
5141 }
5142
5143 if (known.size() > 0) {
5144 list = new String[known.size()];
5145 known.toArray(list);
5146 }
5147 return list;
5148 }
5149
5150 // Select which transport to use for the next backup operation. If the given
5151 // name is not one of the available transports, no action is taken and the method
5152 // returns null.
5153 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005154 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005155
5156 synchronized (mTransports) {
5157 String prevTransport = null;
5158 if (mTransports.get(transport) != null) {
5159 prevTransport = mCurrentTransport;
5160 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005161 Settings.Secure.putString(mContext.getContentResolver(),
5162 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005163 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005164 + " returning " + prevTransport);
5165 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005166 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005167 }
5168 return prevTransport;
5169 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005170 }
5171
Christopher Tatef5e1c292010-12-08 18:40:26 -08005172 // Supply the configuration Intent for the given transport. If the name is not one
5173 // of the available transports, or if the transport does not supply any configuration
5174 // UI, the method returns null.
5175 public Intent getConfigurationIntent(String transportName) {
5176 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5177 "getConfigurationIntent");
5178
5179 synchronized (mTransports) {
5180 final IBackupTransport transport = mTransports.get(transportName);
5181 if (transport != null) {
5182 try {
5183 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005184 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005185 + intent);
5186 return intent;
5187 } catch (RemoteException e) {
5188 /* fall through to return null */
5189 }
5190 }
5191 }
5192
5193 return null;
5194 }
5195
5196 // Supply the configuration summary string for the given transport. If the name is
5197 // not one of the available transports, or if the transport does not supply any
5198 // summary / destination string, the method can return null.
5199 //
5200 // This string is used VERBATIM as the summary text of the relevant Settings item!
5201 public String getDestinationString(String transportName) {
5202 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005203 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005204
5205 synchronized (mTransports) {
5206 final IBackupTransport transport = mTransports.get(transportName);
5207 if (transport != null) {
5208 try {
5209 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005210 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005211 return text;
5212 } catch (RemoteException e) {
5213 /* fall through to return null */
5214 }
5215 }
5216 }
5217
5218 return null;
5219 }
5220
Christopher Tate043dadc2009-06-02 16:11:00 -07005221 // Callback: a requested backup agent has been instantiated. This should only
5222 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005223 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005224 synchronized(mAgentConnectLock) {
5225 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005226 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005227 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5228 mConnectedAgent = agent;
5229 mConnecting = false;
5230 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005231 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005232 + " claiming agent connected");
5233 }
5234 mAgentConnectLock.notifyAll();
5235 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005236 }
5237
5238 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5239 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005240 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005241 public void agentDisconnected(String packageName) {
5242 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005243 synchronized(mAgentConnectLock) {
5244 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5245 mConnectedAgent = null;
5246 mConnecting = false;
5247 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005248 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005249 + " claiming agent disconnected");
5250 }
5251 mAgentConnectLock.notifyAll();
5252 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005253 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005254
Christopher Tate1bb69062010-02-19 17:02:12 -08005255 // An application being installed will need a restore pass, then the Package Manager
5256 // will need to be told when the restore is finished.
5257 public void restoreAtInstall(String packageName, int token) {
5258 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005259 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005260 + " attemping install-time restore");
5261 return;
5262 }
5263
5264 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005265 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005266 + " token=" + Integer.toHexString(token));
5267
Christopher Tatef0872722010-02-25 15:22:48 -08005268 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005269 // okay, we're going to attempt a restore of this package from this restore set.
5270 // The eventual message back into the Package Manager to run the post-install
5271 // steps for 'token' will be issued from the restore handling code.
5272
5273 // We can use a synthetic PackageInfo here because:
5274 // 1. We know it's valid, since the Package Manager supplied the name
5275 // 2. Only the packageName field will be used by the restore code
5276 PackageInfo pkg = new PackageInfo();
5277 pkg.packageName = packageName;
5278
5279 mWakelock.acquire();
5280 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5281 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005282 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005283 mBackupHandler.sendMessage(msg);
5284 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005285 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5286 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005287 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005288 try {
5289 mPackageManagerBinder.finishPackageInstall(token);
5290 } catch (RemoteException e) { /* can't happen */ }
5291 }
5292 }
5293
Christopher Tate8c850b72009-06-07 19:33:20 -07005294 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005295 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5296 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5297 + " transport=" + transport);
5298
5299 boolean needPermission = true;
5300 if (transport == null) {
5301 transport = mCurrentTransport;
5302
5303 if (packageName != null) {
5304 PackageInfo app = null;
5305 try {
5306 app = mPackageManager.getPackageInfo(packageName, 0);
5307 } catch (NameNotFoundException nnf) {
5308 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5309 throw new IllegalArgumentException("Package " + packageName + " not found");
5310 }
5311
5312 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5313 // So: using the current active transport, and the caller has asked
5314 // that its own package will be restored. In this narrow use case
5315 // we do not require the caller to hold the permission.
5316 needPermission = false;
5317 }
5318 }
5319 }
5320
5321 if (needPermission) {
5322 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5323 "beginRestoreSession");
5324 } else {
5325 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5326 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005327
5328 synchronized(this) {
5329 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005330 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005331 return null;
5332 }
Chris Tate44ab8452010-11-16 15:10:49 -08005333 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005334 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005335 }
5336 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005337 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005338
Christopher Tate73a3cb32010-12-13 18:27:26 -08005339 void clearRestoreSession(ActiveRestoreSession currentSession) {
5340 synchronized(this) {
5341 if (currentSession != mActiveRestoreSession) {
5342 Slog.e(TAG, "ending non-current restore session");
5343 } else {
5344 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5345 mActiveRestoreSession = null;
5346 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5347 }
5348 }
5349 }
5350
Christopher Tate44a27902010-01-27 17:15:49 -08005351 // Note that a currently-active backup agent has notified us that it has
5352 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005353 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005354 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005355 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5356 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005357 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005358 op = mCurrentOperations.get(token);
5359 if (op != null) {
5360 op.state = OP_ACKNOWLEDGED;
5361 }
Christopher Tate44a27902010-01-27 17:15:49 -08005362 mCurrentOpLock.notifyAll();
5363 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005364
5365 // The completion callback, if any, is invoked on the handler
5366 if (op != null && op.callback != null) {
5367 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5368 mBackupHandler.sendMessage(msg);
5369 }
Christopher Tate44a27902010-01-27 17:15:49 -08005370 }
5371
Christopher Tate9b3905c2009-06-08 15:24:01 -07005372 // ----- Restore session -----
5373
Christopher Tate80202c82010-01-25 19:37:47 -08005374 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005375 private static final String TAG = "RestoreSession";
5376
Chris Tate44ab8452010-11-16 15:10:49 -08005377 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005378 private IBackupTransport mRestoreTransport = null;
5379 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005380 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005381
Chris Tate44ab8452010-11-16 15:10:49 -08005382 ActiveRestoreSession(String packageName, String transport) {
5383 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005384 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005385 }
5386
5387 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005388 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005390 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005391 if (observer == null) {
5392 throw new IllegalArgumentException("Observer must not be null");
5393 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005394
Christopher Tate73a3cb32010-12-13 18:27:26 -08005395 if (mEnded) {
5396 throw new IllegalStateException("Restore session already ended");
5397 }
5398
Christopher Tate1bb69062010-02-19 17:02:12 -08005399 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005400 try {
Christopher Tate43383042009-07-13 15:17:13 -07005401 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005402 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005403 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005404 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005405 // spin off the transport request to our service thread
5406 mWakelock.acquire();
5407 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5408 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5409 mBackupHandler.sendMessage(msg);
5410 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005411 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005412 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005413 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005414 } finally {
5415 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005416 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005417 }
5418
Christopher Tate84725812010-02-04 15:52:40 -08005419 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005420 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5421 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005422
Chris Tate44ab8452010-11-16 15:10:49 -08005423 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005424 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005425
Christopher Tate73a3cb32010-12-13 18:27:26 -08005426 if (mEnded) {
5427 throw new IllegalStateException("Restore session already ended");
5428 }
5429
Dan Egnor0084da52009-07-29 12:57:16 -07005430 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005431 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5432 return -1;
5433 }
5434
5435 if (mPackageName != null) {
5436 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005437 return -1;
5438 }
5439
Christopher Tate21ab6a52009-09-24 18:01:46 -07005440 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005441 for (int i = 0; i < mRestoreSets.length; i++) {
5442 if (token == mRestoreSets[i].token) {
5443 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005444 mWakelock.acquire();
5445 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005446 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005447 mBackupHandler.sendMessage(msg);
5448 Binder.restoreCallingIdentity(oldId);
5449 return 0;
5450 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005451 }
5452 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005453
Joe Onorato8a9b2202010-02-26 18:56:32 -08005454 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005455 return -1;
5456 }
5457
Christopher Tate284f1bb2011-07-07 14:31:18 -07005458 public synchronized int restoreSome(long token, IRestoreObserver observer,
5459 String[] packages) {
5460 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5461 "performRestore");
5462
5463 if (DEBUG) {
5464 StringBuilder b = new StringBuilder(128);
5465 b.append("restoreSome token=");
5466 b.append(Long.toHexString(token));
5467 b.append(" observer=");
5468 b.append(observer.toString());
5469 b.append(" packages=");
5470 if (packages == null) {
5471 b.append("null");
5472 } else {
5473 b.append('{');
5474 boolean first = true;
5475 for (String s : packages) {
5476 if (!first) {
5477 b.append(", ");
5478 } else first = false;
5479 b.append(s);
5480 }
5481 b.append('}');
5482 }
5483 Slog.d(TAG, b.toString());
5484 }
5485
5486 if (mEnded) {
5487 throw new IllegalStateException("Restore session already ended");
5488 }
5489
5490 if (mRestoreTransport == null || mRestoreSets == null) {
5491 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5492 return -1;
5493 }
5494
5495 if (mPackageName != null) {
5496 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5497 return -1;
5498 }
5499
5500 synchronized (mQueueLock) {
5501 for (int i = 0; i < mRestoreSets.length; i++) {
5502 if (token == mRestoreSets[i].token) {
5503 long oldId = Binder.clearCallingIdentity();
5504 mWakelock.acquire();
5505 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5506 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5507 packages, true);
5508 mBackupHandler.sendMessage(msg);
5509 Binder.restoreCallingIdentity(oldId);
5510 return 0;
5511 }
5512 }
5513 }
5514
5515 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5516 return -1;
5517 }
5518
Christopher Tate84725812010-02-04 15:52:40 -08005519 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005520 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005521
Christopher Tate73a3cb32010-12-13 18:27:26 -08005522 if (mEnded) {
5523 throw new IllegalStateException("Restore session already ended");
5524 }
5525
Chris Tate44ab8452010-11-16 15:10:49 -08005526 if (mPackageName != null) {
5527 if (! mPackageName.equals(packageName)) {
5528 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5529 + " on session for package " + mPackageName);
5530 return -1;
5531 }
5532 }
5533
Christopher Tate84725812010-02-04 15:52:40 -08005534 PackageInfo app = null;
5535 try {
5536 app = mPackageManager.getPackageInfo(packageName, 0);
5537 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005538 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005539 return -1;
5540 }
5541
5542 // If the caller is not privileged and is not coming from the target
5543 // app's uid, throw a permission exception back to the caller.
5544 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5545 Binder.getCallingPid(), Binder.getCallingUid());
5546 if ((perm == PackageManager.PERMISSION_DENIED) &&
5547 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005548 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005549 + " or calling uid=" + Binder.getCallingUid());
5550 throw new SecurityException("No permission to restore other packages");
5551 }
5552
Christopher Tate7d411a32010-02-26 11:27:08 -08005553 // If the package has no backup agent, we obviously cannot proceed
5554 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005555 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005556 return -1;
5557 }
5558
Christopher Tate84725812010-02-04 15:52:40 -08005559 // So far so good; we're allowed to try to restore this package. Now
5560 // check whether there is data for it in the current dataset, falling back
5561 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005562 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005563
5564 // If we didn't come up with a place to look -- no ancestral dataset and
5565 // the app has never been backed up from this device -- there's nothing
5566 // to do but return failure.
5567 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005568 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005569 return -1;
5570 }
5571
5572 // Ready to go: enqueue the restore request and claim success
5573 long oldId = Binder.clearCallingIdentity();
5574 mWakelock.acquire();
5575 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005576 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005577 mBackupHandler.sendMessage(msg);
5578 Binder.restoreCallingIdentity(oldId);
5579 return 0;
5580 }
5581
Christopher Tate73a3cb32010-12-13 18:27:26 -08005582 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5583 class EndRestoreRunnable implements Runnable {
5584 BackupManagerService mBackupManager;
5585 ActiveRestoreSession mSession;
5586
5587 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5588 mBackupManager = manager;
5589 mSession = session;
5590 }
5591
5592 public void run() {
5593 // clean up the session's bookkeeping
5594 synchronized (mSession) {
5595 try {
5596 if (mSession.mRestoreTransport != null) {
5597 mSession.mRestoreTransport.finishRestore();
5598 }
5599 } catch (Exception e) {
5600 Slog.e(TAG, "Error in finishRestore", e);
5601 } finally {
5602 mSession.mRestoreTransport = null;
5603 mSession.mEnded = true;
5604 }
5605 }
5606
5607 // clean up the BackupManagerService side of the bookkeeping
5608 // and cancel any pending timeout message
5609 mBackupManager.clearRestoreSession(mSession);
5610 }
5611 }
5612
Dan Egnor0084da52009-07-29 12:57:16 -07005613 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005614 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005615
Christopher Tate73a3cb32010-12-13 18:27:26 -08005616 if (mEnded) {
5617 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005618 }
5619
Christopher Tate73a3cb32010-12-13 18:27:26 -08005620 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005621 }
5622 }
5623
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005624 @Override
5625 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005626 long identityToken = Binder.clearCallingIdentity();
5627 try {
5628 dumpInternal(pw);
5629 } finally {
5630 Binder.restoreCallingIdentity(identityToken);
5631 }
5632 }
5633
5634 private void dumpInternal(PrintWriter pw) {
Christopher Tateb8491bb2011-09-29 15:13:11 -07005635 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5636 != PackageManager.PERMISSION_GRANTED) {
5637 pw.println("Permission Denial: can't dump Backup Manager service from from pid="
5638 + Binder.getCallingPid()
5639 + ", uid=" + Binder.getCallingUid()
5640 + " without permission "
5641 + android.Manifest.permission.DUMP);
5642 return;
5643 }
5644
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005645 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005646 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005647 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005648 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005649 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate336a6492011-10-05 16:05:43 -07005650 if (mBackupRunning) pw.println("Backup currently running");
5651 pw.println("Last backup pass started: " + mLastBackupPass
Christopher Tate55f931a2009-09-29 17:17:34 -07005652 + " (now = " + System.currentTimeMillis() + ')');
5653 pw.println(" next scheduled: " + mNextBackupPass);
5654
Christopher Tate91717492009-06-26 21:07:13 -07005655 pw.println("Available transports:");
5656 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005657 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5658 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005659 IBackupTransport transport = getTransport(t);
5660 File dir = new File(mBaseStateDir, transport.transportDirName());
5661 pw.println(" destination: " + transport.currentDestinationString());
5662 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005663 for (File f : dir.listFiles()) {
5664 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5665 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005666 } catch (Exception e) {
5667 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005668 pw.println(" Error: " + e);
5669 }
Christopher Tate91717492009-06-26 21:07:13 -07005670 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005671
5672 pw.println("Pending init: " + mPendingInits.size());
5673 for (String s : mPendingInits) {
5674 pw.println(" " + s);
5675 }
5676
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005677 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005678 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005679 for (int i=0; i<N; i++) {
5680 int uid = mBackupParticipants.keyAt(i);
5681 pw.print(" uid: ");
5682 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005683 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5684 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005685 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005686 }
5687 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005688
Christopher Tateb49ceb32010-02-08 16:22:24 -08005689 pw.println("Ancestral packages: "
5690 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005691 if (mAncestralPackages != null) {
5692 for (String pkg : mAncestralPackages) {
5693 pw.println(" " + pkg);
5694 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005695 }
5696
Christopher Tate73e02522009-07-15 14:18:26 -07005697 pw.println("Ever backed up: " + mEverStoredApps.size());
5698 for (String pkg : mEverStoredApps) {
5699 pw.println(" " + pkg);
5700 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005701
5702 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005703 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005704 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005705 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005706 }
5707 }
Christopher Tate487529a2009-04-29 14:03:25 -07005708}