blob: 2938c45e2c535af58be1767e74508ec43eefed19 [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 Tate487529a2009-04-29 14:03:25 -070037import android.content.Context;
38import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070039import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070040import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070041import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070042import android.content.pm.IPackageDataObserver;
Christopher Tatea858cb02011-06-03 12:27:51 -070043import android.content.pm.IPackageDeleteObserver;
Christopher Tate75a99702011-05-18 16:28:19 -070044import android.content.pm.IPackageInstallObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080045import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070046import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070047import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060048import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060049import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070050import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Binder;
Christopher Tate75a99702011-05-18 16:28:19 -070052import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070053import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070054import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080056import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070057import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080058import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070060import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070061import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070062import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070063import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070064import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070065import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070067import android.util.EventLog;
Christopher Tate79ec80d2011-06-24 14:58:49 -070068import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080069import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070070import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080071import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070072import android.util.StringBuilderPrinter;
73
Jason parksa3cdaa52011-01-13 14:15:43 -060074import com.android.internal.backup.BackupConstants;
75import com.android.internal.backup.IBackupTransport;
76import com.android.internal.backup.LocalTransport;
77import com.android.server.PackageManagerBackupAgent.Metadata;
78
Christopher Tate2efd2db2011-07-19 16:32:49 -070079import java.io.BufferedInputStream;
80import java.io.BufferedOutputStream;
81import java.io.ByteArrayOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -070082import java.io.DataInputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070083import java.io.DataOutputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070084import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070085import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070086import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070087import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080088import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070089import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070090import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070091import java.io.InputStream;
Christopher Tate2efd2db2011-07-19 16:32:49 -070092import java.io.OutputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070093import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070094import java.io.RandomAccessFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -070095import java.security.InvalidAlgorithmParameterException;
96import java.security.InvalidKeyException;
97import java.security.Key;
98import java.security.NoSuchAlgorithmException;
99import java.security.SecureRandom;
100import java.security.spec.InvalidKeySpecException;
101import java.security.spec.KeySpec;
Christopher Tate75a99702011-05-18 16:28:19 -0700102import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -0400103import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700104import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -0700105import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -0400106import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -0700107import java.util.HashSet;
108import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -0700109import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -0700110import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800111import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700112import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700113import java.util.zip.Deflater;
114import java.util.zip.DeflaterOutputStream;
Christopher Tate7926a692011-07-11 11:31:57 -0700115import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700116
Christopher Tate2efd2db2011-07-19 16:32:49 -0700117import javax.crypto.BadPaddingException;
118import javax.crypto.Cipher;
119import javax.crypto.CipherInputStream;
120import javax.crypto.CipherOutputStream;
121import javax.crypto.IllegalBlockSizeException;
122import javax.crypto.NoSuchPaddingException;
123import javax.crypto.SecretKey;
124import javax.crypto.SecretKeyFactory;
125import javax.crypto.spec.IvParameterSpec;
126import javax.crypto.spec.PBEKeySpec;
127import javax.crypto.spec.SecretKeySpec;
128
Christopher Tate487529a2009-04-29 14:03:25 -0700129class BackupManagerService extends IBackupManager.Stub {
130 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700131 private static final boolean DEBUG = true;
Christopher Tateb1543a92011-09-07 12:11:09 -0700132 private static final boolean MORE_DEBUG = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700133
134 // Name and current contents version of the full-backup manifest file
135 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
136 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700137 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
138 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700139 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700140
Christopher Tate49401dd2009-07-01 12:34:29 -0700141 // How often we perform a backup pass. Privileged external callers can
142 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700143 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700144
Dan Egnorc1c49c02009-10-30 17:35:39 -0700145 // Random variation in backup scheduling time to avoid server load spikes
146 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
147
Christopher Tate8031a3d2009-07-06 16:36:05 -0700148 // The amount of time between the initial provisioning of the device and
149 // the first backup pass.
150 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
151
Christopher Tate45281862010-03-05 15:46:30 -0800152 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
153 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
154 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700155 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700156 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700157 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700158 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700159 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700160 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
161 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800162 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700163 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
164 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700165
Christopher Tate8e294d42011-08-31 20:37:12 -0700166 // backup task state machine tick
167 static final int MSG_BACKUP_RESTORE_STEP = 20;
168 static final int MSG_OP_COMPLETE = 21;
169
Christopher Tatec7b31e32009-06-10 15:49:30 -0700170 // Timeout interval for deciding that a bind or clear-data has taken too long
171 static final long TIMEOUT_INTERVAL = 10 * 1000;
172
Christopher Tate44a27902010-01-27 17:15:49 -0800173 // Timeout intervals for agent backup & restore operations
174 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700175 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700176 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800177 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
178
Christopher Tate2efd2db2011-07-19 16:32:49 -0700179 // User confirmation timeout for a full backup/restore operation. It's this long in
180 // order to give them time to enter the backup password.
181 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700182
Christopher Tate487529a2009-04-29 14:03:25 -0700183 private Context mContext;
184 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800185 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700186 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700187 private PowerManager mPowerManager;
188 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800189 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700190
Christopher Tate73e02522009-07-15 14:18:26 -0700191 boolean mEnabled; // access to this is synchronized on 'this'
192 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800193 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700194 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800195 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
196 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700197 PendingIntent mRunBackupIntent, mRunInitIntent;
198 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700199 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700200 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700201 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700202 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700203 class BackupRequest {
Christopher Tatecc55f812011-08-16 16:06:53 -0700204 public String packageName;
Christopher Tateaa088442009-06-16 18:25:46 -0700205
Christopher Tatecc55f812011-08-16 16:06:53 -0700206 BackupRequest(String pkgName) {
207 packageName = pkgName;
Christopher Tate46758122009-05-06 11:22:00 -0700208 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700209
210 public String toString() {
Christopher Tatecc55f812011-08-16 16:06:53 -0700211 return "BackupRequest{pkg=" + packageName + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700212 }
Christopher Tate46758122009-05-06 11:22:00 -0700213 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800214 // Backups that we haven't started yet. Keys are package names.
215 HashMap<String,BackupRequest> mPendingBackups
216 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700217
218 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700219 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700220
221 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700222 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700223
Christopher Tate043dadc2009-06-02 16:11:00 -0700224 // The thread performing the sequence of queued backups binds to each app's agent
225 // in succession. Bind notifications are asynchronously delivered through the
226 // Activity Manager; use this lock object to signal when a requested binding has
227 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700228 final Object mAgentConnectLock = new Object();
229 IBackupAgent mConnectedAgent;
230 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700231 volatile long mLastBackupPass;
232 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700233
Christopher Tate55f931a2009-09-29 17:17:34 -0700234 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700235 final Object mClearDataLock = new Object();
236 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700237
Christopher Tate91717492009-06-26 21:07:13 -0700238 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700239 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700240 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700241 String mCurrentTransport;
242 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800243 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700244
Christopher Tate2d449afe2010-03-29 19:14:24 -0700245 class RestoreGetSetsParams {
246 public IBackupTransport transport;
247 public ActiveRestoreSession session;
248 public IRestoreObserver observer;
249
250 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
251 IRestoreObserver _observer) {
252 transport = _transport;
253 session = _session;
254 observer = _observer;
255 }
256 }
257
Christopher Tate73e02522009-07-15 14:18:26 -0700258 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700259 public IBackupTransport transport;
260 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700261 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800262 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800263 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700264 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700265 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800266
267 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700268 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800269 transport = _transport;
270 observer = _obs;
271 token = _token;
272 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800273 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700274 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700275 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800276 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700277
Chris Tate249345b2010-10-29 12:57:04 -0700278 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
279 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700280 transport = _transport;
281 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700282 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800283 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800284 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700285 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700286 filterSet = null;
287 }
288
289 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
290 String[] _filterSet, boolean _needFullBackup) {
291 transport = _transport;
292 observer = _obs;
293 token = _token;
294 pkgInfo = null;
295 pmToken = 0;
296 needFullBackup = _needFullBackup;
297 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700298 }
299 }
300
Christopher Tate73e02522009-07-15 14:18:26 -0700301 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700302 public IBackupTransport transport;
303 public PackageInfo packageInfo;
304
305 ClearParams(IBackupTransport _transport, PackageInfo _info) {
306 transport = _transport;
307 packageInfo = _info;
308 }
309 }
310
Christopher Tate4a627c72011-04-01 14:43:32 -0700311 class FullParams {
312 public ParcelFileDescriptor fd;
313 public final AtomicBoolean latch;
314 public IFullBackupRestoreObserver observer;
Christopher Tate728a1c42011-07-28 18:03:03 -0700315 public String curPassword; // filled in by the confirmation step
316 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700317
318 FullParams() {
319 latch = new AtomicBoolean(false);
320 }
321 }
322
323 class FullBackupParams extends FullParams {
324 public boolean includeApks;
325 public boolean includeShared;
326 public boolean allApps;
327 public String[] packages;
328
329 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
330 boolean doAllApps, String[] pkgList) {
331 fd = output;
332 includeApks = saveApks;
333 includeShared = saveShared;
334 allApps = doAllApps;
335 packages = pkgList;
336 }
337 }
338
339 class FullRestoreParams extends FullParams {
340 FullRestoreParams(ParcelFileDescriptor input) {
341 fd = input;
342 }
343 }
344
Christopher Tate44a27902010-01-27 17:15:49 -0800345 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
346 // token is the index of the entry in the pending-operations list.
347 static final int OP_PENDING = 0;
348 static final int OP_ACKNOWLEDGED = 1;
349 static final int OP_TIMEOUT = -1;
350
Christopher Tate8e294d42011-08-31 20:37:12 -0700351 class Operation {
352 public int state;
353 public BackupRestoreTask callback;
354
355 Operation(int initialState, BackupRestoreTask callbackObj) {
356 state = initialState;
357 callback = callbackObj;
358 }
359 }
360 final SparseArray<Operation> mCurrentOperations = new SparseArray<Operation>();
Christopher Tate44a27902010-01-27 17:15:49 -0800361 final Object mCurrentOpLock = new Object();
362 final Random mTokenGenerator = new Random();
363
Christopher Tate4a627c72011-04-01 14:43:32 -0700364 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
365
Christopher Tate5cb400b2009-06-25 16:03:14 -0700366 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700367 File mBaseStateDir;
368 File mDataDir;
369 File mJournalDir;
370 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700371
Christopher Tate2efd2db2011-07-19 16:32:49 -0700372 // Backup password, if any, and the file where it's saved. What is stored is not the
373 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
374 // persisted) salt. Validation is performed by running the challenge text through the
375 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
376 // the saved hash string, then the challenge text matches the originally supplied
377 // password text.
378 private final SecureRandom mRng = new SecureRandom();
379 private String mPasswordHash;
380 private File mPasswordHashFile;
381 private byte[] mPasswordSalt;
382
383 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
384 static final int PBKDF2_HASH_ROUNDS = 10000;
385 static final int PBKDF2_KEY_SIZE = 256; // bits
386 static final int PBKDF2_SALT_SIZE = 512; // bits
387 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
388
Christopher Tate84725812010-02-04 15:52:40 -0800389 // Keep a log of all the apps we've ever backed up, and what the
390 // dataset tokens are for both the current backup dataset and
391 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700392 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700393 HashSet<String> mEverStoredApps = new HashSet<String>();
394
Christopher Tateb49ceb32010-02-08 16:22:24 -0800395 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800396 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800397 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800398 long mAncestralToken = 0;
399 long mCurrentToken = 0;
400
Christopher Tate4cc86e12009-09-21 19:36:51 -0700401 // Persistently track the need to do a full init
402 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
403 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700404
Christopher Tate4a627c72011-04-01 14:43:32 -0700405 // Utility: build a new random integer token
406 int generateToken() {
407 int token;
408 do {
409 synchronized (mTokenGenerator) {
410 token = mTokenGenerator.nextInt();
411 }
412 } while (token < 0);
413 return token;
414 }
415
Christopher Tate44a27902010-01-27 17:15:49 -0800416 // ----- Asynchronous backup/restore handler thread -----
417
418 private class BackupHandler extends Handler {
419 public BackupHandler(Looper looper) {
420 super(looper);
421 }
422
423 public void handleMessage(Message msg) {
424
425 switch (msg.what) {
426 case MSG_RUN_BACKUP:
427 {
428 mLastBackupPass = System.currentTimeMillis();
429 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
430
431 IBackupTransport transport = getTransport(mCurrentTransport);
432 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800433 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800434 mWakelock.release();
435 break;
436 }
437
438 // snapshot the pending-backup set and work on that
439 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800440 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800441 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800442 // Do we have any work to do? Construct the work queue
443 // then release the synchronization lock to actually run
444 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800445 if (mPendingBackups.size() > 0) {
446 for (BackupRequest b: mPendingBackups.values()) {
447 queue.add(b);
448 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800449 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800450 mPendingBackups.clear();
451
452 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800453 mJournal = null;
454
Christopher Tate44a27902010-01-27 17:15:49 -0800455 }
456 }
Christopher Tatec61da312010-02-05 10:41:27 -0800457
Christopher Tate8e294d42011-08-31 20:37:12 -0700458 // At this point, we have started a new journal file, and the old
459 // file identity is being passed to the backup processing task.
460 // When it completes successfully, that old journal file will be
461 // deleted. If we crash prior to that, the old journal is parsed
462 // at next boot and the journaled requests fulfilled.
Christopher Tatec61da312010-02-05 10:41:27 -0800463 if (queue.size() > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -0700464 // Spin up a backup state sequence and set it running
465 PerformBackupTask pbt = new PerformBackupTask(transport, queue, oldJournal);
466 Message pbtMessage = obtainMessage(MSG_BACKUP_RESTORE_STEP, pbt);
467 sendMessage(pbtMessage);
Christopher Tatec61da312010-02-05 10:41:27 -0800468 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800469 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800470 mWakelock.release();
471 }
Christopher Tate44a27902010-01-27 17:15:49 -0800472 break;
473 }
474
Christopher Tate8e294d42011-08-31 20:37:12 -0700475 case MSG_BACKUP_RESTORE_STEP:
476 {
477 try {
478 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
479 if (MORE_DEBUG) Slog.v(TAG, "Got next step for " + task + ", executing");
480 task.execute();
481 } catch (ClassCastException e) {
482 Slog.e(TAG, "Invalid backup task in flight, obj=" + msg.obj);
483 }
484 break;
485 }
486
487 case MSG_OP_COMPLETE:
488 {
489 try {
Christopher Tate2982d062011-09-06 20:35:24 -0700490 BackupRestoreTask task = (BackupRestoreTask) msg.obj;
491 task.operationComplete();
Christopher Tate8e294d42011-08-31 20:37:12 -0700492 } catch (ClassCastException e) {
493 Slog.e(TAG, "Invalid completion in flight, obj=" + msg.obj);
494 }
495 break;
496 }
497
Christopher Tate44a27902010-01-27 17:15:49 -0800498 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700499 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700500 // TODO: refactor full backup to be a looper-based state machine
501 // similar to normal backup/restore.
Christopher Tate4a627c72011-04-01 14:43:32 -0700502 FullBackupParams params = (FullBackupParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700503 PerformFullBackupTask task = new PerformFullBackupTask(params.fd,
504 params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700505 params.includeShared, params.curPassword, params.encryptPassword,
Christopher Tatea28e8542011-09-12 13:45:21 -0700506 params.allApps, params.packages, params.latch);
507 (new Thread(task)).start();
Christopher Tate44a27902010-01-27 17:15:49 -0800508 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700509 }
Christopher Tate44a27902010-01-27 17:15:49 -0800510
511 case MSG_RUN_RESTORE:
512 {
513 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800514 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700515 PerformRestoreTask task = new PerformRestoreTask(
516 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700517 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700518 params.needFullBackup, params.filterSet);
519 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
520 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800521 break;
522 }
523
Christopher Tate75a99702011-05-18 16:28:19 -0700524 case MSG_RUN_FULL_RESTORE:
525 {
Christopher Tatea28e8542011-09-12 13:45:21 -0700526 // TODO: refactor full restore to be a looper-based state machine
527 // similar to normal backup/restore.
Christopher Tate75a99702011-05-18 16:28:19 -0700528 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tatea28e8542011-09-12 13:45:21 -0700529 PerformFullRestoreTask task = new PerformFullRestoreTask(params.fd,
530 params.curPassword, params.encryptPassword,
531 params.observer, params.latch);
532 (new Thread(task)).start();
Christopher Tate75a99702011-05-18 16:28:19 -0700533 break;
534 }
535
Christopher Tate44a27902010-01-27 17:15:49 -0800536 case MSG_RUN_CLEAR:
537 {
538 ClearParams params = (ClearParams)msg.obj;
539 (new PerformClearTask(params.transport, params.packageInfo)).run();
540 break;
541 }
542
543 case MSG_RUN_INITIALIZE:
544 {
545 HashSet<String> queue;
546
547 // Snapshot the pending-init queue and work on that
548 synchronized (mQueueLock) {
549 queue = new HashSet<String>(mPendingInits);
550 mPendingInits.clear();
551 }
552
553 (new PerformInitializeTask(queue)).run();
554 break;
555 }
556
Christopher Tate2d449afe2010-03-29 19:14:24 -0700557 case MSG_RUN_GET_RESTORE_SETS:
558 {
559 // Like other async operations, this is entered with the wakelock held
560 RestoreSet[] sets = null;
561 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
562 try {
563 sets = params.transport.getAvailableRestoreSets();
564 // cache the result in the active session
565 synchronized (params.session) {
566 params.session.mRestoreSets = sets;
567 }
568 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
569 } catch (Exception e) {
570 Slog.e(TAG, "Error from transport getting set list");
571 } finally {
572 if (params.observer != null) {
573 try {
574 params.observer.restoreSetsAvailable(sets);
575 } catch (RemoteException re) {
576 Slog.e(TAG, "Unable to report listing to observer");
577 } catch (Exception e) {
578 Slog.e(TAG, "Restore observer threw", e);
579 }
580 }
581
Christopher Tate2a935092011-03-03 17:30:32 -0800582 // Done: reset the session timeout clock
583 removeMessages(MSG_RESTORE_TIMEOUT);
584 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
585
Christopher Tate2d449afe2010-03-29 19:14:24 -0700586 mWakelock.release();
587 }
588 break;
589 }
590
Christopher Tate44a27902010-01-27 17:15:49 -0800591 case MSG_TIMEOUT:
592 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700593 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800594 break;
595 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800596
597 case MSG_RESTORE_TIMEOUT:
598 {
599 synchronized (BackupManagerService.this) {
600 if (mActiveRestoreSession != null) {
601 // Client app left the restore session dangling. We know that it
602 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700603 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800604 // up now.
605 Slog.w(TAG, "Restore session timed out; aborting");
606 post(mActiveRestoreSession.new EndRestoreRunnable(
607 BackupManagerService.this, mActiveRestoreSession));
608 }
609 }
610 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700611
612 case MSG_FULL_CONFIRMATION_TIMEOUT:
613 {
614 synchronized (mFullConfirmations) {
615 FullParams params = mFullConfirmations.get(msg.arg1);
616 if (params != null) {
617 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
618
619 // Release the waiter; timeout == completion
620 signalFullBackupRestoreCompletion(params);
621
622 // Remove the token from the set
623 mFullConfirmations.delete(msg.arg1);
624
625 // Report a timeout to the observer, if any
626 if (params.observer != null) {
627 try {
628 params.observer.onTimeout();
629 } catch (RemoteException e) {
630 /* don't care if the app has gone away */
631 }
632 }
633 } else {
634 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
635 }
636 }
637 break;
638 }
Christopher Tate44a27902010-01-27 17:15:49 -0800639 }
640 }
641 }
642
643 // ----- Main service implementation -----
644
Christopher Tate487529a2009-04-29 14:03:25 -0700645 public BackupManagerService(Context context) {
646 mContext = context;
647 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700648 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700649 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700650
Christopher Tateb6787f22009-07-02 17:40:45 -0700651 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
652 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
653
Christopher Tate44a27902010-01-27 17:15:49 -0800654 mBackupManagerBinder = asInterface(asBinder());
655
656 // spin up the backup/restore handler thread
657 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
658 mHandlerThread.start();
659 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
660
Christopher Tate22b87872009-05-04 16:41:53 -0700661 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700662 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700663 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700664 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700665 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800666 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800667 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800668 // If Encrypted file systems is enabled or disabled, this call will return the
669 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600670 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800671 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700672 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700673
Christopher Tate2efd2db2011-07-19 16:32:49 -0700674 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
675 if (mPasswordHashFile.exists()) {
676 FileInputStream fin = null;
677 DataInputStream in = null;
678 try {
679 fin = new FileInputStream(mPasswordHashFile);
680 in = new DataInputStream(new BufferedInputStream(fin));
681 // integer length of the salt array, followed by the salt,
682 // then the hex pw hash string
683 int saltLen = in.readInt();
684 byte[] salt = new byte[saltLen];
685 in.readFully(salt);
686 mPasswordHash = in.readUTF();
687 mPasswordSalt = salt;
688 } catch (IOException e) {
689 Slog.e(TAG, "Unable to read saved backup pw hash");
690 } finally {
691 try {
692 if (in != null) in.close();
693 if (fin != null) fin.close();
694 } catch (IOException e) {
695 Slog.w(TAG, "Unable to close streams");
696 }
697 }
698 }
699
Christopher Tate4cc86e12009-09-21 19:36:51 -0700700 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700701 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700702 IntentFilter filter = new IntentFilter();
703 filter.addAction(RUN_BACKUP_ACTION);
704 context.registerReceiver(mRunBackupReceiver, filter,
705 android.Manifest.permission.BACKUP, null);
706
707 mRunInitReceiver = new RunInitializeReceiver();
708 filter = new IntentFilter();
709 filter.addAction(RUN_INITIALIZE_ACTION);
710 context.registerReceiver(mRunInitReceiver, filter,
711 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700712
713 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700714 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
715 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
716
Christopher Tate4cc86e12009-09-21 19:36:51 -0700717 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
718 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
719 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
720
Christopher Tatecde87f42009-06-12 12:55:53 -0700721 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700722 mJournalDir = new File(mBaseStateDir, "pending");
723 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700724 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700725
Christopher Tate73e02522009-07-15 14:18:26 -0700726 // Set up the various sorts of package tracking we do
727 initPackageTracking();
728
Christopher Tateabce4e82009-06-18 18:35:32 -0700729 // Build our mapping of uid to backup client services. This implicitly
730 // schedules a backup pass on the Package Manager metadata the first
731 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700732 synchronized (mBackupParticipants) {
733 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700734 }
735
Dan Egnor87a02bc2009-06-17 02:30:10 -0700736 // Set up our transport options and initialize the default transport
737 // TODO: Have transports register themselves somehow?
738 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700739 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700740 ComponentName localName = new ComponentName(context, LocalTransport.class);
741 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700742
Christopher Tate91717492009-06-26 21:07:13 -0700743 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700744 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
745 Settings.Secure.BACKUP_TRANSPORT);
746 if ("".equals(mCurrentTransport)) {
747 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700748 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800749 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700750
751 // Attach to the Google backup transport. When this comes up, it will set
752 // itself as the current transport because we explicitly reset mCurrentTransport
753 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700754 ComponentName transportComponent = new ComponentName("com.google.android.backup",
755 "com.google.android.backup.BackupTransportService");
756 try {
757 // If there's something out there that is supposed to be the Google
758 // backup transport, make sure it's legitimately part of the OS build
759 // and not an app lying about its package name.
760 ApplicationInfo info = mPackageManager.getApplicationInfo(
761 transportComponent.getPackageName(), 0);
762 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
763 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
764 Intent intent = new Intent().setComponent(transportComponent);
765 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
766 } else {
767 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
768 }
769 } catch (PackageManager.NameNotFoundException nnf) {
770 // No such package? No binding.
771 if (DEBUG) Slog.v(TAG, "Google transport not present");
772 }
Christopher Tateaa088442009-06-16 18:25:46 -0700773
Christopher Tatecde87f42009-06-12 12:55:53 -0700774 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700775 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700776 parseLeftoverJournals();
777
Christopher Tateb6787f22009-07-02 17:40:45 -0700778 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700779 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700780
781 // Start the backup passes going
782 setBackupEnabled(areEnabled);
783 }
784
785 private class RunBackupReceiver extends BroadcastReceiver {
786 public void onReceive(Context context, Intent intent) {
787 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700788 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700789 if (mPendingInits.size() > 0) {
790 // If there are pending init operations, we process those
791 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800792 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700793 try {
794 mAlarmManager.cancel(mRunInitIntent);
795 mRunInitIntent.send();
796 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800797 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700798 // can't really do more than bail here
799 }
800 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800801 // Don't run backups now if we're disabled or not yet
802 // fully set up.
803 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800804 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700805
806 // Acquire the wakelock and pass it to the backup thread. it will
807 // be released once backup concludes.
808 mWakelock.acquire();
809
810 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
811 mBackupHandler.sendMessage(msg);
812 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800813 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700814 }
815 }
816 }
817 }
818 }
819 }
820
821 private class RunInitializeReceiver extends BroadcastReceiver {
822 public void onReceive(Context context, Intent intent) {
823 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
824 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800825 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700826
827 // Acquire the wakelock and pass it to the init thread. it will
828 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700829 mWakelock.acquire();
830
Christopher Tate4cc86e12009-09-21 19:36:51 -0700831 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700832 mBackupHandler.sendMessage(msg);
833 }
834 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700835 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700836 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700837
Christopher Tate73e02522009-07-15 14:18:26 -0700838 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800839 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700840
Christopher Tate84725812010-02-04 15:52:40 -0800841 // Remember our ancestral dataset
842 mTokenFile = new File(mBaseStateDir, "ancestral");
843 try {
844 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800845 int version = tf.readInt();
846 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
847 mAncestralToken = tf.readLong();
848 mCurrentToken = tf.readLong();
849
850 int numPackages = tf.readInt();
851 if (numPackages >= 0) {
852 mAncestralPackages = new HashSet<String>();
853 for (int i = 0; i < numPackages; i++) {
854 String pkgName = tf.readUTF();
855 mAncestralPackages.add(pkgName);
856 }
857 }
858 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800859 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800860 } catch (FileNotFoundException fnf) {
861 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800862 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800863 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800864 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800865 }
866
Christopher Tatee97e8072009-07-15 16:45:50 -0700867 // Keep a log of what apps we've ever backed up. Because we might have
868 // rebooted in the middle of an operation that was removing something from
869 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700870 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700871 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700872
Christopher Tatee97e8072009-07-15 16:45:50 -0700873 // If we were in the middle of removing something from the ever-backed-up
874 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700875 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700876 if (tempProcessedFile.exists()) {
877 tempProcessedFile.delete();
878 }
879
Dan Egnor852f8e42009-09-30 11:20:45 -0700880 // If there are previous contents, parse them out then start a new
881 // file to continue the recordkeeping.
882 if (mEverStored.exists()) {
883 RandomAccessFile temp = null;
884 RandomAccessFile in = null;
885
886 try {
887 temp = new RandomAccessFile(tempProcessedFile, "rws");
888 in = new RandomAccessFile(mEverStored, "r");
889
890 while (true) {
891 PackageInfo info;
892 String pkg = in.readUTF();
893 try {
894 info = mPackageManager.getPackageInfo(pkg, 0);
895 mEverStoredApps.add(pkg);
896 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700897 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700898 } catch (NameNotFoundException e) {
899 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700900 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700901 }
902 }
903 } catch (EOFException e) {
904 // Once we've rewritten the backup history log, atomically replace the
905 // old one with the new one then reopen the file for continuing use.
906 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800907 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700908 }
909 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800910 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700911 } finally {
912 try { if (temp != null) temp.close(); } catch (IOException e) {}
913 try { if (in != null) in.close(); } catch (IOException e) {}
914 }
915 }
916
Christopher Tate73e02522009-07-15 14:18:26 -0700917 // Register for broadcasts about package install, etc., so we can
918 // update the provider list.
919 IntentFilter filter = new IntentFilter();
920 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
921 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700922 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700923 filter.addDataScheme("package");
924 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800925 // Register for events related to sdcard installation.
926 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800927 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
928 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800929 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700930 }
931
Christopher Tatecde87f42009-06-12 12:55:53 -0700932 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700933 for (File f : mJournalDir.listFiles()) {
934 if (mJournal == null || f.compareTo(mJournal) != 0) {
935 // This isn't the current journal, so it must be a leftover. Read
936 // out the package names mentioned there and schedule them for
937 // backup.
938 RandomAccessFile in = null;
939 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400940 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700941 in = new RandomAccessFile(f, "r");
942 while (true) {
943 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400944 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700945 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700946 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700947 } catch (EOFException e) {
948 // no more data; we're done
949 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800950 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700951 } finally {
952 // close/delete the file
953 try { if (in != null) in.close(); } catch (IOException e) {}
954 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700955 }
956 }
957 }
958 }
959
Christopher Tate2efd2db2011-07-19 16:32:49 -0700960 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
961 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
962 }
963
964 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
965 try {
966 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
967 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
968 return keyFactory.generateSecret(ks);
969 } catch (InvalidKeySpecException e) {
970 Slog.e(TAG, "Invalid key spec for PBKDF2!");
971 } catch (NoSuchAlgorithmException e) {
972 Slog.e(TAG, "PBKDF2 unavailable!");
973 }
974 return null;
975 }
976
977 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
978 SecretKey key = buildPasswordKey(pw, salt, rounds);
979 if (key != null) {
980 return byteArrayToHex(key.getEncoded());
981 }
982 return null;
983 }
984
985 private String byteArrayToHex(byte[] data) {
986 StringBuilder buf = new StringBuilder(data.length * 2);
987 for (int i = 0; i < data.length; i++) {
988 buf.append(Byte.toHexString(data[i], true));
989 }
990 return buf.toString();
991 }
992
993 private byte[] hexToByteArray(String digits) {
994 final int bytes = digits.length() / 2;
995 if (2*bytes != digits.length()) {
996 throw new IllegalArgumentException("Hex string must have an even number of digits");
997 }
998
999 byte[] result = new byte[bytes];
1000 for (int i = 0; i < digits.length(); i += 2) {
1001 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
1002 }
1003 return result;
1004 }
1005
1006 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
1007 char[] mkAsChar = new char[pwBytes.length];
1008 for (int i = 0; i < pwBytes.length; i++) {
1009 mkAsChar[i] = (char) pwBytes[i];
1010 }
1011
1012 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1013 return checksum.getEncoded();
1014 }
1015
1016 // Used for generating random salts or passwords
1017 private byte[] randomBytes(int bits) {
1018 byte[] array = new byte[bits / 8];
1019 mRng.nextBytes(array);
1020 return array;
1021 }
1022
1023 // Backup password management
1024 boolean passwordMatchesSaved(String candidatePw, int rounds) {
1025 if (mPasswordHash == null) {
1026 // no current password case -- require that 'currentPw' be null or empty
1027 if (candidatePw == null || "".equals(candidatePw)) {
1028 return true;
1029 } // else the non-empty candidate does not match the empty stored pw
1030 } else {
1031 // hash the stated current pw and compare to the stored one
1032 if (candidatePw != null && candidatePw.length() > 0) {
1033 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1034 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1035 // candidate hash matches the stored hash -- the password matches
1036 return true;
1037 }
1038 } // else the stored pw is nonempty but the candidate is empty; no match
1039 }
1040 return false;
1041 }
1042
1043 @Override
1044 public boolean setBackupPassword(String currentPw, String newPw) {
1045 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1046 "setBackupPassword");
1047
1048 // If the supplied pw doesn't hash to the the saved one, fail
1049 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1050 return false;
1051 }
1052
1053 // Clearing the password is okay
1054 if (newPw == null || newPw.isEmpty()) {
1055 if (mPasswordHashFile.exists()) {
1056 if (!mPasswordHashFile.delete()) {
1057 // Unable to delete the old pw file, so fail
1058 Slog.e(TAG, "Unable to clear backup password");
1059 return false;
1060 }
1061 }
1062 mPasswordHash = null;
1063 mPasswordSalt = null;
1064 return true;
1065 }
1066
1067 try {
1068 // Okay, build the hash of the new backup password
1069 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1070 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1071
1072 OutputStream pwf = null, buffer = null;
1073 DataOutputStream out = null;
1074 try {
1075 pwf = new FileOutputStream(mPasswordHashFile);
1076 buffer = new BufferedOutputStream(pwf);
1077 out = new DataOutputStream(buffer);
1078 // integer length of the salt array, followed by the salt,
1079 // then the hex pw hash string
1080 out.writeInt(salt.length);
1081 out.write(salt);
1082 out.writeUTF(newPwHash);
1083 out.flush();
1084 mPasswordHash = newPwHash;
1085 mPasswordSalt = salt;
1086 return true;
1087 } finally {
1088 if (out != null) out.close();
1089 if (buffer != null) buffer.close();
1090 if (pwf != null) pwf.close();
1091 }
1092 } catch (IOException e) {
1093 Slog.e(TAG, "Unable to set backup password");
1094 }
1095 return false;
1096 }
1097
1098 @Override
1099 public boolean hasBackupPassword() {
1100 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1101 "hasBackupPassword");
1102 return (mPasswordHash != null && mPasswordHash.length() > 0);
1103 }
1104
Christopher Tate4cc86e12009-09-21 19:36:51 -07001105 // Maintain persistent state around whether need to do an initialize operation.
1106 // Must be called with the queue lock held.
1107 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001108 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001109 + " on transport " + transportName);
1110 try {
1111 IBackupTransport transport = getTransport(transportName);
1112 String transportDirName = transport.transportDirName();
1113 File stateDir = new File(mBaseStateDir, transportDirName);
1114 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1115
1116 if (isPending) {
1117 // We need an init before we can proceed with sending backup data.
1118 // Record that with an entry in our set of pending inits, as well as
1119 // journaling it via creation of a sentinel file.
1120 mPendingInits.add(transportName);
1121 try {
1122 (new FileOutputStream(initPendingFile)).close();
1123 } catch (IOException ioe) {
1124 // Something is badly wrong with our permissions; just try to move on
1125 }
1126 } else {
1127 // No more initialization needed; wipe the journal and reset our state.
1128 initPendingFile.delete();
1129 mPendingInits.remove(transportName);
1130 }
1131 } catch (RemoteException e) {
1132 // can't happen; the transport is local
1133 }
1134 }
1135
Christopher Tated55e18a2009-09-21 10:12:59 -07001136 // Reset all of our bookkeeping, in response to having been told that
1137 // the backend data has been wiped [due to idle expiry, for example],
1138 // so we must re-upload all saved settings.
1139 void resetBackupState(File stateFileDir) {
1140 synchronized (mQueueLock) {
1141 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001142 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001143 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001144
Christopher Tate84725812010-02-04 15:52:40 -08001145 mCurrentToken = 0;
1146 writeRestoreTokens();
1147
Christopher Tated55e18a2009-09-21 10:12:59 -07001148 // Remove all the state files
1149 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001150 // ... but don't touch the needs-init sentinel
1151 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1152 sf.delete();
1153 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001154 }
Christopher Tate45597642011-04-04 16:59:21 -07001155 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001156
Christopher Tate45597642011-04-04 16:59:21 -07001157 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001158 synchronized (mBackupParticipants) {
1159 int N = mBackupParticipants.size();
1160 for (int i=0; i<N; i++) {
1161 int uid = mBackupParticipants.keyAt(i);
1162 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1163 for (ApplicationInfo app: participants) {
1164 dataChangedImpl(app.packageName);
1165 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001166 }
1167 }
1168 }
1169
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001170 // Add a transport to our set of available backends. If 'transport' is null, this
1171 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001172 private void registerTransport(String name, IBackupTransport transport) {
1173 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001174 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001175 if (transport != null) {
1176 mTransports.put(name, transport);
1177 } else {
1178 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001179 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001180 mCurrentTransport = null;
1181 }
1182 // Nothing further to do in the unregistration case
1183 return;
1184 }
Christopher Tate91717492009-06-26 21:07:13 -07001185 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001186
1187 // If the init sentinel file exists, we need to be sure to perform the init
1188 // as soon as practical. We also create the state directory at registration
1189 // time to ensure it's present from the outset.
1190 try {
1191 String transportName = transport.transportDirName();
1192 File stateDir = new File(mBaseStateDir, transportName);
1193 stateDir.mkdirs();
1194
1195 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1196 if (initSentinel.exists()) {
1197 synchronized (mQueueLock) {
1198 mPendingInits.add(transportName);
1199
1200 // TODO: pick a better starting time than now + 1 minute
1201 long delay = 1000 * 60; // one minute, in milliseconds
1202 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1203 System.currentTimeMillis() + delay, mRunInitIntent);
1204 }
1205 }
1206 } catch (RemoteException e) {
1207 // can't happen, the transport is local
1208 }
Christopher Tate91717492009-06-26 21:07:13 -07001209 }
1210
Christopher Tate3799bc22009-05-06 16:13:56 -07001211 // ----- Track installation/removal of packages -----
1212 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1213 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001214 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001215
Christopher Tate3799bc22009-05-06 16:13:56 -07001216 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001217 boolean replacing = false;
1218 boolean added = false;
1219 Bundle extras = intent.getExtras();
1220 String pkgList[] = null;
1221 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001222 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1223 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001224 Uri uri = intent.getData();
1225 if (uri == null) {
1226 return;
1227 }
1228 String pkgName = uri.getSchemeSpecificPart();
1229 if (pkgName != null) {
1230 pkgList = new String[] { pkgName };
1231 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001232 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1233 // use the existing "add with replacement" logic
1234 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1235 added = replacing = true;
1236 } else {
1237 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1238 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1239 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001240 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001241 added = true;
1242 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001243 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001244 added = false;
1245 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1246 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001247
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001248 if (pkgList == null || pkgList.length == 0) {
1249 return;
1250 }
1251 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001252 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001253 for (String pkgName : pkgList) {
1254 if (replacing) {
1255 // The package was just upgraded
1256 updatePackageParticipantsLocked(pkgName);
1257 } else {
1258 // The package was just added
1259 addPackageParticipantsLocked(pkgName);
1260 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001261 }
1262 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001263 } else {
1264 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001265 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1266 } else {
1267 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001268 for (String pkgName : pkgList) {
1269 removePackageParticipantsLocked(pkgName);
1270 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001271 }
1272 }
1273 }
1274 }
1275 };
1276
Dan Egnor87a02bc2009-06-17 02:30:10 -07001277 // ----- Track connection to GoogleBackupTransport service -----
1278 ServiceConnection mGoogleConnection = new ServiceConnection() {
1279 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001280 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001281 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001282 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001283 }
1284
1285 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001286 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001287 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001288 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001289 }
1290 };
1291
Christopher Tate181fafa2009-05-14 11:12:14 -07001292 // Add the backup agents in the given package to our set of known backup participants.
1293 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001294 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001295 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001296 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001297 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001298 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001299 }
1300
Christopher Tate181fafa2009-05-14 11:12:14 -07001301 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001302 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001303 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001304 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001305 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001306 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001307 + " uid=" + p.applicationInfo.uid
1308 + " killAfterRestore="
1309 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001310 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001311 }
1312 }
1313
Dan Egnorefe52642009-06-24 00:16:33 -07001314 for (PackageInfo pkg : targetPkgs) {
1315 if (packageName == null || pkg.packageName.equals(packageName)) {
1316 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001317 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001318 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001319 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001320 mBackupParticipants.put(uid, set);
1321 }
Dan Egnorefe52642009-06-24 00:16:33 -07001322 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001323
1324 // If we've never seen this app before, schedule a backup for it
1325 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001326 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001327 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001328 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001329 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001330 }
Christopher Tate487529a2009-04-29 14:03:25 -07001331 }
1332 }
1333
Christopher Tate6785dd82009-06-18 15:58:25 -07001334 // Remove the given package's entry from our known active set. If
1335 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001336 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001337 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001338 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001339 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001340 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001341 } else {
1342 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001343 List<PackageInfo> knownPackages = allAgentPackages();
1344 for (PackageInfo pkg : knownPackages) {
1345 allApps.add(pkg.packageName);
1346 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001347 }
1348 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001349 }
1350
Joe Onorato8ad02812009-05-13 01:41:44 -04001351 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001352 List<String> allPackageNames) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001353 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001354 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001355 + ") removing " + allPackageNames.size() + " entries");
1356 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001357 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001358 }
1359 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001360 for (String pkg : allPackageNames) {
1361 if (packageName == null || pkg.equals(packageName)) {
1362 int uid = -1;
1363 try {
1364 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1365 uid = info.applicationInfo.uid;
1366 } catch (NameNotFoundException e) {
1367 // we don't know this package name, so just skip it for now
1368 continue;
1369 }
1370
Christopher Tate181fafa2009-05-14 11:12:14 -07001371 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001372 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001373 // Find the existing entry with the same package name, and remove it.
1374 // We can't just remove(app) because the instances are different.
1375 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001376 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001377 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001378 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001379 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001380 break;
1381 }
1382 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001383 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001384 mBackupParticipants.delete(uid);
1385 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001386 }
1387 }
1388 }
1389 }
1390
Christopher Tate181fafa2009-05-14 11:12:14 -07001391 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001392 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001393 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001394 int flags = PackageManager.GET_SIGNATURES;
1395 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1396 int N = packages.size();
1397 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001398 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001399 try {
1400 ApplicationInfo app = pkg.applicationInfo;
1401 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001402 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001403 packages.remove(a);
1404 }
1405 else {
1406 // we will need the shared library path, so look that up and store it here
1407 app = mPackageManager.getApplicationInfo(pkg.packageName,
1408 PackageManager.GET_SHARED_LIBRARY_FILES);
1409 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1410 }
1411 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001412 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001413 }
1414 }
Dan Egnorefe52642009-06-24 00:16:33 -07001415 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001416 }
Christopher Tateaa088442009-06-16 18:25:46 -07001417
Christopher Tate3799bc22009-05-06 16:13:56 -07001418 // Reset the given package's known backup participants. Unlike add/remove, the update
1419 // action cannot be passed a null package name.
1420 void updatePackageParticipantsLocked(String packageName) {
1421 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001422 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001423 return;
1424 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001425 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001426
1427 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001428 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001429 List<String> allAppNames = new ArrayList<String>();
1430 for (PackageInfo pkg : allApps) {
1431 allAppNames.add(pkg.packageName);
1432 }
1433 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001434 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001435 }
1436
Christopher Tate84725812010-02-04 15:52:40 -08001437 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001438 // backed up at least once
1439 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001440 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1441
1442 synchronized (mEverStoredApps) {
1443 if (!mEverStoredApps.add(packageName)) return;
1444
1445 RandomAccessFile out = null;
1446 try {
1447 out = new RandomAccessFile(mEverStored, "rws");
1448 out.seek(out.length());
1449 out.writeUTF(packageName);
1450 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001451 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001452 } finally {
1453 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001454 }
1455 }
1456 }
1457
Christopher Tatee97e8072009-07-15 16:45:50 -07001458 // Remove our awareness of having ever backed up the given package
1459 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001460 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1461 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001462
Dan Egnor852f8e42009-09-30 11:20:45 -07001463 synchronized (mEverStoredApps) {
1464 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1465 // we'll recognize on initialization time that the package no longer
1466 // exists and fix it up then.
1467 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1468 RandomAccessFile known = null;
1469 try {
1470 known = new RandomAccessFile(tempKnownFile, "rws");
1471 mEverStoredApps.remove(packageName);
1472 for (String s : mEverStoredApps) {
1473 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001474 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001475 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001476 known.close();
1477 known = null;
1478 if (!tempKnownFile.renameTo(mEverStored)) {
1479 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1480 }
1481 } catch (IOException e) {
1482 // Bad: we couldn't create the new copy. For safety's sake we
1483 // abandon the whole process and remove all what's-backed-up
1484 // state entirely, meaning we'll force a backup pass for every
1485 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001486 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001487 mEverStoredApps.clear();
1488 tempKnownFile.delete();
1489 mEverStored.delete();
1490 } finally {
1491 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001492 }
1493 }
1494 }
1495
Christopher Tateb49ceb32010-02-08 16:22:24 -08001496 // Persistently record the current and ancestral backup tokens as well
1497 // as the set of packages with data [supposedly] available in the
1498 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001499 void writeRestoreTokens() {
1500 try {
1501 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001502
1503 // First, the version number of this record, for futureproofing
1504 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1505
1506 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001507 af.writeLong(mAncestralToken);
1508 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001509
1510 // Now write the set of ancestral packages
1511 if (mAncestralPackages == null) {
1512 af.writeInt(-1);
1513 } else {
1514 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001515 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001516 for (String pkgName : mAncestralPackages) {
1517 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001518 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001519 }
1520 }
Christopher Tate84725812010-02-04 15:52:40 -08001521 af.close();
1522 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001523 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001524 }
1525 }
1526
Dan Egnor87a02bc2009-06-17 02:30:10 -07001527 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001528 private IBackupTransport getTransport(String transportName) {
1529 synchronized (mTransports) {
1530 IBackupTransport transport = mTransports.get(transportName);
1531 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001532 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001533 }
1534 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001535 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001536 }
1537
Christopher Tatedf01dea2009-06-09 20:45:02 -07001538 // fire off a backup agent, blocking until it attaches or times out
1539 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1540 IBackupAgent agent = null;
1541 synchronized(mAgentConnectLock) {
1542 mConnecting = true;
1543 mConnectedAgent = null;
1544 try {
1545 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001546 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001547
1548 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001549 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001550 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1551 while (mConnecting && mConnectedAgent == null
1552 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001553 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001554 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001555 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001556 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001557 return null;
1558 }
1559 }
1560
1561 // if we timed out with no connect, abort and move on
1562 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001563 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001564 return null;
1565 }
1566 agent = mConnectedAgent;
1567 }
1568 } catch (RemoteException e) {
1569 // can't happen
1570 }
1571 }
1572 return agent;
1573 }
1574
Christopher Tatec7b31e32009-06-10 15:49:30 -07001575 // clear an application's data, blocking until the operation completes or times out
1576 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001577 // Don't wipe packages marked allowClearUserData=false
1578 try {
1579 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1580 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001581 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001582 + packageName);
1583 return;
1584 }
1585 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001586 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001587 return;
1588 }
1589
Christopher Tatec7b31e32009-06-10 15:49:30 -07001590 ClearDataObserver observer = new ClearDataObserver();
1591
1592 synchronized(mClearDataLock) {
1593 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001594 try {
1595 mActivityManager.clearApplicationUserData(packageName, observer);
1596 } catch (RemoteException e) {
1597 // can't happen because the activity manager is in this process
1598 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001599
1600 // only wait 10 seconds for the clear data to happen
1601 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1602 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1603 try {
1604 mClearDataLock.wait(5000);
1605 } catch (InterruptedException e) {
1606 // won't happen, but still.
1607 mClearingData = false;
1608 }
1609 }
1610 }
1611 }
1612
1613 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001614 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001615 synchronized(mClearDataLock) {
1616 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001617 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001618 }
1619 }
1620 }
1621
Christopher Tate1bb69062010-02-19 17:02:12 -08001622 // Get the restore-set token for the best-available restore set for this package:
1623 // the active set if possible, else the ancestral one. Returns zero if none available.
1624 long getAvailableRestoreToken(String packageName) {
1625 long token = mAncestralToken;
1626 synchronized (mQueueLock) {
1627 if (mEverStoredApps.contains(packageName)) {
1628 token = mCurrentToken;
1629 }
1630 }
1631 return token;
1632 }
1633
Christopher Tate44a27902010-01-27 17:15:49 -08001634 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001635 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1636
1637 interface BackupRestoreTask {
1638 // Execute one tick of whatever state machine the task implements
1639 void execute();
1640
1641 // An operation that wanted a callback has completed
1642 void operationComplete();
1643
1644 // An operation that wanted a callback has timed out
1645 void handleTimeout();
1646 }
1647
1648 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1649 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1650 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001651 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001652 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1653
1654 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1655 mBackupHandler.sendMessageDelayed(msg, interval);
1656 }
1657 }
1658
1659 // synchronous waiter case
1660 boolean waitUntilOperationComplete(int token) {
1661 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1662 + Integer.toHexString(token));
1663 int finalState = OP_PENDING;
1664 Operation op = null;
1665 synchronized (mCurrentOpLock) {
1666 while (true) {
1667 op = mCurrentOperations.get(token);
1668 if (op == null) {
1669 // mysterious disappearance: treat as success with no callback
1670 break;
1671 } else {
1672 if (op.state == OP_PENDING) {
1673 try {
1674 mCurrentOpLock.wait();
1675 } catch (InterruptedException e) {}
1676 // When the wait is notified we loop around and recheck the current state
1677 } else {
1678 // No longer pending; we're done
1679 finalState = op.state;
1680 break;
1681 }
Christopher Tate44a27902010-01-27 17:15:49 -08001682 }
Christopher Tate44a27902010-01-27 17:15:49 -08001683 }
1684 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001685
Christopher Tate44a27902010-01-27 17:15:49 -08001686 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001687 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001688 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001689 return finalState == OP_ACKNOWLEDGED;
1690 }
1691
Christopher Tate8e294d42011-08-31 20:37:12 -07001692 void handleTimeout(int token, Object obj) {
1693 // Notify any synchronous waiters
1694 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001695 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001696 op = mCurrentOperations.get(token);
1697 if (MORE_DEBUG) {
1698 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1699 + " but no op found");
1700 }
1701 int state = (op != null) ? op.state : OP_TIMEOUT;
1702 if (state == OP_PENDING) {
1703 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1704 op.state = OP_TIMEOUT;
1705 mCurrentOperations.put(token, op);
1706 }
1707 mCurrentOpLock.notifyAll();
1708 }
1709
1710 // If there's a TimeoutHandler for this event, call it
1711 if (op != null && op.callback != null) {
1712 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001713 }
Christopher Tate44a27902010-01-27 17:15:49 -08001714 }
1715
Christopher Tate043dadc2009-06-02 16:11:00 -07001716 // ----- Back up a set of applications via a worker thread -----
1717
Christopher Tate8e294d42011-08-31 20:37:12 -07001718 enum BackupState {
1719 INITIAL,
1720 RUNNING_QUEUE,
1721 FINAL
1722 }
1723
1724 class PerformBackupTask implements BackupRestoreTask {
1725 private static final String TAG = "PerformBackupTask";
1726
Christopher Tateaa088442009-06-16 18:25:46 -07001727 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001728 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001729 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001730 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001731 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001732 BackupState mCurrentState;
1733
1734 // carried information about the current in-flight operation
1735 PackageInfo mCurrentPackage;
1736 File mSavedStateName;
1737 File mBackupDataName;
1738 File mNewStateName;
1739 ParcelFileDescriptor mSavedState;
1740 ParcelFileDescriptor mBackupData;
1741 ParcelFileDescriptor mNewState;
1742 int mStatus;
1743 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001744
Christopher Tate44a27902010-01-27 17:15:49 -08001745 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001746 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001747 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001748 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001749 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001750
1751 try {
1752 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1753 } catch (RemoteException e) {
1754 // can't happen; the transport is local
1755 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001756
1757 mCurrentState = BackupState.INITIAL;
1758 mFinished = false;
Christopher Tate043dadc2009-06-02 16:11:00 -07001759 }
1760
Christopher Tate8e294d42011-08-31 20:37:12 -07001761 // Main entry point: perform one chunk of work, updating the state as appropriate
1762 // and reposting the next chunk to the primary backup handler thread.
1763 @Override
1764 public void execute() {
1765 switch (mCurrentState) {
1766 case INITIAL:
1767 beginBackup();
1768 break;
1769
1770 case RUNNING_QUEUE:
1771 invokeNextAgent();
1772 break;
1773
1774 case FINAL:
1775 if (!mFinished) finalizeBackup();
1776 else {
1777 Slog.e(TAG, "Duplicate finish");
1778 }
Christopher Tate2982d062011-09-06 20:35:24 -07001779 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001780 break;
1781 }
1782 }
1783
1784 // We're starting a backup pass. Initialize the transport and send
1785 // the PM metadata blob if we haven't already.
1786 void beginBackup() {
1787 mStatus = BackupConstants.TRANSPORT_OK;
1788
1789 // Sanity check: if the queue is empty we have no work to do.
1790 if (mOriginalQueue.isEmpty()) {
1791 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
1792 return;
1793 }
1794
1795 // We need to retain the original queue contents in case of transport
1796 // failure, but we want a working copy that we can manipulate along
1797 // the way.
1798 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1799
Joe Onorato8a9b2202010-02-26 18:56:32 -08001800 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001801
Christopher Tate8e294d42011-08-31 20:37:12 -07001802 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001803 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001804 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001805
Dan Egnor852f8e42009-09-30 11:20:45 -07001806 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001807 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001808 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001809 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001810 mStatus = mTransport.initializeDevice();
1811 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001812 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001813 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001814 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001815 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001816 }
Dan Egnor01445162009-09-21 17:04:05 -07001817 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001818
1819 // The package manager doesn't have a proper <application> etc, but since
1820 // it's running here in the system process we can just set up its agent
1821 // directly and use a synthetic BackupRequest. We always run this pass
1822 // because it's cheap and this way we guarantee that we don't get out of
1823 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001824 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001825 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1826 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001827 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001828 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1829 }
Christopher Tate90967f42009-09-20 15:28:33 -07001830
Christopher Tate8e294d42011-08-31 20:37:12 -07001831 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1832 // The backend reports that our dataset has been wiped. Note this in
1833 // the event log; the no-success code below will reset the backup
1834 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001835 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001836 }
1837 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001838 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001839 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001840 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001841 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1842 // metadata and its completion/timeout callback will continue the state
1843 // machine chain. If it failed that won't happen; we handle that now.
1844 if (mStatus != BackupConstants.TRANSPORT_OK) {
1845 // if things went wrong at this point, we need to
1846 // restage everything and try again later.
1847 resetBackupState(mStateDir); // Just to make sure.
1848 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001849 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001850 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001851 }
1852
Christopher Tate8e294d42011-08-31 20:37:12 -07001853 // Transport has been initialized and the PM metadata submitted successfully
1854 // if that was warranted. Now we process the single next thing in the queue.
1855 void invokeNextAgent() {
1856 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001857
Christopher Tate8e294d42011-08-31 20:37:12 -07001858 // Sanity check that we have work to do. If not, skip to the end where
1859 // we reestablish the wakelock invariants etc.
1860 if (mQueue.isEmpty()) {
1861 Slog.e(TAG, "Running queue but it's empty!");
1862 executeNextState(BackupState.FINAL);
1863 return;
1864 }
1865
1866 // pop the entry we're going to process on this step
1867 BackupRequest request = mQueue.get(0);
1868 mQueue.remove(0);
1869
1870 Slog.d(TAG, "starting agent for backup of " + request);
1871
1872 // Verify that the requested app exists; it might be something that
1873 // requested a backup but was then uninstalled. The request was
1874 // journalled and rather than tamper with the journal it's safer
1875 // to sanity-check here. This also gives us the classname of the
1876 // package's backup agent.
1877 try {
1878 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1879 PackageManager.GET_SIGNATURES);
Christopher Tatec28083a2010-12-14 16:16:44 -08001880
Christopher Tate043dadc2009-06-02 16:11:00 -07001881 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001882 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001883 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1884 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001885 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001886 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001887 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1888 // at this point we'll either get a completion callback from the
1889 // agent, or a timeout message on the main handler. either way, we're
1890 // done here as long as we're successful so far.
1891 } else {
1892 // Timeout waiting for the agent
1893 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07001894 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001895 } catch (SecurityException ex) {
1896 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001897 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07001898 mStatus = BackupConstants.AGENT_ERROR;
1899 }
1900 } catch (NameNotFoundException e) {
1901 Slog.d(TAG, "Package does not exist; skipping");
1902 } finally {
1903 mWakelock.setWorkSource(null);
1904
1905 // If there was an agent error, no timeout/completion handling will occur.
1906 // That means we need to deal with the next state ourselves.
1907 if (mStatus != BackupConstants.TRANSPORT_OK) {
1908 BackupState nextState = BackupState.RUNNING_QUEUE;
1909
1910 // An agent-level failure means we reenqueue this one agent for
1911 // a later retry, but otherwise proceed normally.
1912 if (mStatus == BackupConstants.AGENT_ERROR) {
1913 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
1914 + " - restaging");
1915 dataChangedImpl(request.packageName);
1916 mStatus = BackupConstants.TRANSPORT_OK;
1917 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
1918 } else if (mStatus != BackupConstants.TRANSPORT_OK) {
1919 // Transport-level failure means we reenqueue everything
1920 revertAndEndBackup();
1921 nextState = BackupState.FINAL;
1922 }
1923
1924 executeNextState(nextState);
Christopher Tate043dadc2009-06-02 16:11:00 -07001925 }
1926 }
1927 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001928
Christopher Tate8e294d42011-08-31 20:37:12 -07001929 void finalizeBackup() {
1930 // Either backup was successful, in which case we of course do not need
1931 // this pass's journal any more; or it failed, in which case we just
1932 // re-enqueued all of these packages in the current active journal.
1933 // Either way, we no longer need this pass's journal.
1934 if (mJournal != null && !mJournal.delete()) {
1935 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
1936 }
1937
1938 // If everything actually went through and this is the first time we've
1939 // done a backup, we can now record what the current backup dataset token
1940 // is.
1941 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
1942 try {
1943 mCurrentToken = mTransport.getCurrentRestoreSet();
1944 } catch (RemoteException e) {} // can't happen
1945 writeRestoreTokens();
1946 }
1947
1948 // Set up the next backup pass
1949 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1950 backupNow();
1951 }
1952
1953 // Only once we're entirely finished do we release the wakelock
1954 Slog.i(TAG, "Backup pass finished.");
1955 mWakelock.release();
1956 }
1957
1958 // Invoke an agent's doBackup() and start a timeout message spinning on the main
1959 // handler in case it doesn't get back to us.
1960 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07001961 IBackupTransport transport) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001962 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001963
Christopher Tate8e294d42011-08-31 20:37:12 -07001964 mSavedStateName = new File(mStateDir, packageName);
1965 mBackupDataName = new File(mDataDir, packageName + ".data");
1966 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001967
Christopher Tate8e294d42011-08-31 20:37:12 -07001968 mSavedState = null;
1969 mBackupData = null;
1970 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001971
Christopher Tate4a627c72011-04-01 14:43:32 -07001972 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001973 try {
1974 // Look up the package info & signatures. This is first so that if it
1975 // throws an exception, there's no file setup yet that would need to
1976 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001977 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001978 // The metadata 'package' is synthetic; construct one and make
1979 // sure our global state is pointed at it
1980 mCurrentPackage = new PackageInfo();
1981 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07001982 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001983
Christopher Tatec7b31e32009-06-10 15:49:30 -07001984 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001985 // the saved-state "file". This is by definition an incremental,
1986 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07001987 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07001988 ParcelFileDescriptor.MODE_READ_ONLY |
1989 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001990
Christopher Tate8e294d42011-08-31 20:37:12 -07001991 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001992 ParcelFileDescriptor.MODE_READ_WRITE |
1993 ParcelFileDescriptor.MODE_CREATE |
1994 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001995
Christopher Tate8e294d42011-08-31 20:37:12 -07001996 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001997 ParcelFileDescriptor.MODE_READ_WRITE |
1998 ParcelFileDescriptor.MODE_CREATE |
1999 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002000
Christopher Tate44a27902010-01-27 17:15:49 -08002001 // Initiate the target's backup pass
Christopher Tate8e294d42011-08-31 20:37:12 -07002002 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
2003 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002004 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002005 Slog.e(TAG, "Error invoking for backup on " + packageName);
2006 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
2007 e.toString());
2008 agentErrorCleanup();
2009 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002010 }
2011
Christopher Tate8e294d42011-08-31 20:37:12 -07002012 // At this point the agent is off and running. The next thing to happen will
2013 // either be a callback from the agent, at which point we'll process its data
2014 // for transport, or a timeout. Either way the next phase will happen in
2015 // response to the TimeoutHandler interface callbacks.
2016 return BackupConstants.TRANSPORT_OK;
2017 }
2018
2019 @Override
2020 public void operationComplete() {
2021 // Okay, the agent successfully reported back to us. Spin the data off to the
2022 // transport and proceed with the next stage.
2023 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2024 + mCurrentPackage.packageName);
2025 mBackupHandler.removeMessages(MSG_TIMEOUT);
2026 clearAgentState();
2027
2028 ParcelFileDescriptor backupData = null;
2029 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002030 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002031 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002032 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002033 if (mStatus == BackupConstants.TRANSPORT_OK) {
2034 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002035 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate8e294d42011-08-31 20:37:12 -07002036 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002037 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002038
Dan Egnor83861e72009-09-17 16:17:55 -07002039 // TODO - We call finishBackup() for each application backed up, because
2040 // we need to know now whether it succeeded or failed. Instead, we should
2041 // hold off on finishBackup() until the end, which implies holding off on
2042 // renaming *all* the output state files (see below) until that happens.
2043
Christopher Tate8e294d42011-08-31 20:37:12 -07002044 if (mStatus == BackupConstants.TRANSPORT_OK) {
2045 mStatus = mTransport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07002046 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002047 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002048 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002049 }
2050
2051 // After successful transport, delete the now-stale data
2052 // and juggle the files so that next time we supply the agent
2053 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002054 if (mStatus == BackupConstants.TRANSPORT_OK) {
2055 mBackupDataName.delete();
2056 mNewStateName.renameTo(mSavedStateName);
2057 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2058 mCurrentPackage.packageName, size);
2059 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002060 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002061 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2062 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002063 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002064 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002065 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2066 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2067 mCurrentPackage.packageName);
2068 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002069 } finally {
2070 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002071 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002072
Christopher Tate8e294d42011-08-31 20:37:12 -07002073 // If we encountered an error here it's a transport-level failure. That
2074 // means we need to halt everything and reschedule everything for next time.
2075 final BackupState nextState;
2076 if (mStatus != BackupConstants.TRANSPORT_OK) {
2077 revertAndEndBackup();
2078 nextState = BackupState.FINAL;
2079 } else {
2080 // Success! Proceed with the next app if any, otherwise we're done.
2081 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2082 }
2083
2084 executeNextState(nextState);
2085 }
2086
2087 @Override
2088 public void handleTimeout() {
2089 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2090 // it for the next time we run a backup pass.
2091 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2092 // fail repeatedly (i.e. have proved themselves to be buggy).
2093 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2094 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2095 "timeout");
2096 agentErrorCleanup();
2097 dataChangedImpl(mCurrentPackage.packageName);
2098 }
2099
2100 void revertAndEndBackup() {
2101 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2102 for (BackupRequest request : mOriginalQueue) {
2103 dataChangedImpl(request.packageName);
2104 }
2105 // We also want to reset the backup schedule based on whatever
2106 // the transport suggests by way of retry/backoff time.
2107 restartBackupAlarm();
2108 }
2109
2110 void agentErrorCleanup() {
2111 mBackupDataName.delete();
2112 mNewStateName.delete();
2113 clearAgentState();
2114
2115 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2116 }
2117
2118 // Cleanup common to both success and failure cases
2119 void clearAgentState() {
2120 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2121 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2122 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2123 mSavedState = mBackupData = mNewState = null;
2124 synchronized (mCurrentOpLock) {
2125 mCurrentOperations.clear();
2126 }
2127
2128 // If this was a pseudopackage there's no associated Activity Manager state
2129 if (mCurrentPackage.applicationInfo != null) {
2130 try { // unbind even on timeout, just in case
2131 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2132 } catch (RemoteException e) {}
2133 }
2134 }
2135
2136 void restartBackupAlarm() {
2137 synchronized (mQueueLock) {
2138 try {
2139 startBackupAlarmsLocked(mTransport.requestBackupTime());
2140 } catch (RemoteException e) { /* cannot happen */ }
2141 }
2142 }
2143
2144 void executeNextState(BackupState nextState) {
2145 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2146 + this + " nextState=" + nextState);
2147 mCurrentState = nextState;
2148 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2149 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002150 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002151 }
2152
Christopher Tatedf01dea2009-06-09 20:45:02 -07002153
Christopher Tate4a627c72011-04-01 14:43:32 -07002154 // ----- Full backup to a file/socket -----
2155
2156 class PerformFullBackupTask implements Runnable {
2157 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002158 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002159 IFullBackupRestoreObserver mObserver;
2160 boolean mIncludeApks;
2161 boolean mIncludeShared;
2162 boolean mAllApps;
2163 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002164 String mCurrentPassword;
2165 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002166 AtomicBoolean mLatchObject;
2167 File mFilesDir;
2168 File mManifestFile;
2169
Christopher Tate7926a692011-07-11 11:31:57 -07002170 class FullBackupRunner implements Runnable {
2171 PackageInfo mPackage;
2172 IBackupAgent mAgent;
2173 ParcelFileDescriptor mPipe;
2174 int mToken;
2175 boolean mSendApk;
2176
2177 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2178 int token, boolean sendApk) throws IOException {
2179 mPackage = pack;
2180 mAgent = agent;
2181 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2182 mToken = token;
2183 mSendApk = sendApk;
2184 }
2185
2186 @Override
2187 public void run() {
2188 try {
2189 BackupDataOutput output = new BackupDataOutput(
2190 mPipe.getFileDescriptor());
2191
Christopher Tatec58efa62011-08-01 19:20:14 -07002192 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07002193 writeAppManifest(mPackage, mManifestFile, mSendApk);
2194 FullBackup.backupToTar(mPackage.packageName, null, null,
2195 mFilesDir.getAbsolutePath(),
2196 mManifestFile.getAbsolutePath(),
2197 output);
2198
2199 if (mSendApk) {
2200 writeApkToBackup(mPackage, output);
2201 }
2202
Christopher Tatec58efa62011-08-01 19:20:14 -07002203 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002204 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002205 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2206 } catch (IOException e) {
2207 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2208 } catch (RemoteException e) {
2209 Slog.e(TAG, "Remote agent vanished during full backup of "
2210 + mPackage.packageName);
2211 } finally {
2212 try {
2213 mPipe.close();
2214 } catch (IOException e) {}
2215 }
2216 }
2217 }
2218
Christopher Tate4a627c72011-04-01 14:43:32 -07002219 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002220 boolean includeApks, boolean includeShared, String curPassword,
2221 String encryptPassword, boolean doAllApps, String[] packages,
2222 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002223 mOutputFile = fd;
2224 mObserver = observer;
2225 mIncludeApks = includeApks;
2226 mIncludeShared = includeShared;
2227 mAllApps = doAllApps;
2228 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002229 mCurrentPassword = curPassword;
2230 // when backing up, if there is a current backup password, we require that
2231 // the user use a nonempty encryption password as well. if one is supplied
2232 // in the UI we use that, but if the UI was left empty we fall back to the
2233 // current backup password (which was supplied by the user as well).
2234 if (encryptPassword == null || "".equals(encryptPassword)) {
2235 mEncryptPassword = curPassword;
2236 } else {
2237 mEncryptPassword = encryptPassword;
2238 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002239 mLatchObject = latch;
2240
2241 mFilesDir = new File("/data/system");
2242 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2243 }
2244
2245 @Override
2246 public void run() {
2247 final List<PackageInfo> packagesToBackup;
2248
Christopher Tateb0628bf2011-06-02 15:08:13 -07002249 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002250 sendStartBackup();
2251
2252 // doAllApps supersedes the package set if any
2253 if (mAllApps) {
2254 packagesToBackup = mPackageManager.getInstalledPackages(
2255 PackageManager.GET_SIGNATURES);
2256 } else {
2257 packagesToBackup = new ArrayList<PackageInfo>();
2258 for (String pkgName : mPackages) {
2259 try {
2260 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2261 PackageManager.GET_SIGNATURES));
2262 } catch (NameNotFoundException e) {
2263 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2264 }
2265 }
2266 }
2267
Christopher Tatea858cb02011-06-03 12:27:51 -07002268 // Cull any packages that have indicated that backups are not permitted.
2269 for (int i = 0; i < packagesToBackup.size(); ) {
2270 PackageInfo info = packagesToBackup.get(i);
2271 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2272 packagesToBackup.remove(i);
2273 } else {
2274 i++;
2275 }
2276 }
2277
Christopher Tate7926a692011-07-11 11:31:57 -07002278 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002279 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002280
Christopher Tate4a627c72011-04-01 14:43:32 -07002281 PackageInfo pkg = null;
2282 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002283 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002284 boolean compressing = COMPRESS_FULL_BACKUPS;
2285 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002286
Christopher Tateeef4ae42011-08-05 13:15:53 -07002287 // Verify that the given password matches the currently-active
2288 // backup password, if any
2289 if (hasBackupPassword()) {
2290 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2291 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2292 return;
2293 }
2294 }
2295
Christopher Tate7bdb0962011-07-13 19:30:21 -07002296 // Write the global file header. All strings are UTF-8 encoded; lines end
2297 // with a '\n' byte. Actual backup data begins immediately following the
2298 // final '\n'.
2299 //
2300 // line 1: "ANDROID BACKUP"
2301 // line 2: backup file format version, currently "1"
2302 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002303 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2304 //
2305 // When line 4 is not "none", then additional header data follows:
2306 //
2307 // line 5: user password salt [hex]
2308 // line 6: master key checksum salt [hex]
2309 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2310 // line 8: IV of the user key [hex]
2311 // line 9: master key blob [hex]
2312 // IV of the master key, master key itself, master key checksum hash
2313 //
2314 // The master key checksum is the master key plus its checksum salt, run through
2315 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2316 // correct password for decrypting the archive: the master key decrypted from
2317 // the archive using the user-supplied password is also run through PBKDF2 in
2318 // this way, and if the result does not match the checksum as stored in the
2319 // archive, then we know that the user-supplied password does not match the
2320 // archive's.
2321 StringBuilder headerbuf = new StringBuilder(1024);
2322
Christopher Tate7bdb0962011-07-13 19:30:21 -07002323 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002324 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2325 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002326
2327 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002328 // Set up the encryption stage if appropriate, and emit the correct header
2329 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002330 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2331 } else {
2332 headerbuf.append("none\n");
2333 }
2334
Christopher Tate7bdb0962011-07-13 19:30:21 -07002335 byte[] header = headerbuf.toString().getBytes("UTF-8");
2336 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002337
2338 // Set up the compression stage feeding into the encryption stage (if any)
2339 if (compressing) {
2340 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2341 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2342 }
2343
2344 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002345 } catch (Exception e) {
2346 // Should never happen!
2347 Slog.e(TAG, "Unable to emit archive header", e);
2348 return;
2349 }
2350
Christopher Tateb0628bf2011-06-02 15:08:13 -07002351 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002352 int N = packagesToBackup.size();
2353 for (int i = 0; i < N; i++) {
2354 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002355 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002356 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002357
Christopher Tate6853fcf2011-08-10 17:52:21 -07002358 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002359 if (mIncludeShared) {
2360 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002361 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002362
2363 // Done!
2364 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002365 } catch (RemoteException e) {
2366 Slog.e(TAG, "App died during full backup");
2367 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002368 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002369 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002370 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002371 mOutputFile.close();
2372 } catch (IOException e) {
2373 /* nothing we can do about this */
2374 }
2375 synchronized (mCurrentOpLock) {
2376 mCurrentOperations.clear();
2377 }
2378 synchronized (mLatchObject) {
2379 mLatchObject.set(true);
2380 mLatchObject.notifyAll();
2381 }
2382 sendEndBackup();
2383 mWakelock.release();
2384 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2385 }
2386 }
2387
Christopher Tate2efd2db2011-07-19 16:32:49 -07002388 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2389 OutputStream ofstream) throws Exception {
2390 // User key will be used to encrypt the master key.
2391 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002392 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002393 PBKDF2_HASH_ROUNDS);
2394
2395 // the master key is random for each backup
2396 byte[] masterPw = new byte[256 / 8];
2397 mRng.nextBytes(masterPw);
2398 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2399
2400 // primary encryption of the datastream with the random key
2401 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2402 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2403 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2404 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2405
2406 // line 4: name of encryption algorithm
2407 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2408 headerbuf.append('\n');
2409 // line 5: user password salt [hex]
2410 headerbuf.append(byteArrayToHex(newUserSalt));
2411 headerbuf.append('\n');
2412 // line 6: master key checksum salt [hex]
2413 headerbuf.append(byteArrayToHex(checksumSalt));
2414 headerbuf.append('\n');
2415 // line 7: number of PBKDF2 rounds used [decimal]
2416 headerbuf.append(PBKDF2_HASH_ROUNDS);
2417 headerbuf.append('\n');
2418
2419 // line 8: IV of the user key [hex]
2420 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2421 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2422
2423 byte[] IV = mkC.getIV();
2424 headerbuf.append(byteArrayToHex(IV));
2425 headerbuf.append('\n');
2426
2427 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2428 // [byte] IV length = Niv
2429 // [array of Niv bytes] IV itself
2430 // [byte] master key length = Nmk
2431 // [array of Nmk bytes] master key itself
2432 // [byte] MK checksum hash length = Nck
2433 // [array of Nck bytes] master key checksum hash
2434 //
2435 // The checksum is the (master key + checksum salt), run through the
2436 // stated number of PBKDF2 rounds
2437 IV = c.getIV();
2438 byte[] mk = masterKeySpec.getEncoded();
2439 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2440 checksumSalt, PBKDF2_HASH_ROUNDS);
2441
2442 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2443 + checksum.length + 3);
2444 DataOutputStream mkOut = new DataOutputStream(blob);
2445 mkOut.writeByte(IV.length);
2446 mkOut.write(IV);
2447 mkOut.writeByte(mk.length);
2448 mkOut.write(mk);
2449 mkOut.writeByte(checksum.length);
2450 mkOut.write(checksum);
2451 mkOut.flush();
2452 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2453 headerbuf.append(byteArrayToHex(encryptedMk));
2454 headerbuf.append('\n');
2455
2456 return finalOutput;
2457 }
2458
2459 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002460 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002461 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2462
2463 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2464 IApplicationThread.BACKUP_MODE_FULL);
2465 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002466 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002467 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002468 pipes = ParcelFileDescriptor.createPipe();
2469
Christopher Tateb0628bf2011-06-02 15:08:13 -07002470 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002471 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002472 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2473 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2474 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2475
2476 sendOnBackupPackage(pkg.packageName);
2477
Christopher Tate7926a692011-07-11 11:31:57 -07002478 final int token = generateToken();
2479 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2480 token, sendApk);
2481 pipes[1].close(); // the runner has dup'd it
2482 pipes[1] = null;
2483 Thread t = new Thread(runner);
2484 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002485
Christopher Tate7926a692011-07-11 11:31:57 -07002486 // Now pull data from the app and stuff it into the compressor
2487 try {
2488 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2489 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002490
Christopher Tate7926a692011-07-11 11:31:57 -07002491 byte[] buffer = new byte[16 * 1024];
2492 int chunkTotal;
2493 while ((chunkTotal = in.readInt()) > 0) {
2494 while (chunkTotal > 0) {
2495 int toRead = (chunkTotal > buffer.length)
2496 ? buffer.length : chunkTotal;
2497 int nRead = in.read(buffer, 0, toRead);
2498 out.write(buffer, 0, nRead);
2499 chunkTotal -= nRead;
2500 }
2501 }
2502 } catch (IOException e) {
2503 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002504 }
2505
Christopher Tateb0628bf2011-06-02 15:08:13 -07002506 if (!waitUntilOperationComplete(token)) {
2507 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2508 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002509 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002510 }
Christopher Tate7926a692011-07-11 11:31:57 -07002511
Christopher Tateb0628bf2011-06-02 15:08:13 -07002512 } catch (IOException e) {
2513 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002514 } finally {
2515 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002516 // flush after every package
2517 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002518 if (pipes != null) {
2519 if (pipes[0] != null) pipes[0].close();
2520 if (pipes[1] != null) pipes[1].close();
2521 }
Christopher Tate7926a692011-07-11 11:31:57 -07002522 } catch (IOException e) {
2523 Slog.w(TAG, "Error bringing down backup stack");
2524 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002525 }
2526 } else {
2527 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2528 }
2529 tearDown(pkg);
2530 }
2531
Christopher Tate79ec80d2011-06-24 14:58:49 -07002532 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2533 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2534 final String appSourceDir = pkg.applicationInfo.sourceDir;
2535 final String apkDir = new File(appSourceDir).getParent();
2536 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2537 apkDir, appSourceDir, output);
2538
2539 // Save associated .obb content if it exists and we did save the apk
2540 // check for .obb and save those too
2541 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2542 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002543 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002544 File[] obbFiles = obbDir.listFiles();
2545 if (obbFiles != null) {
2546 final String obbDirName = obbDir.getAbsolutePath();
2547 for (File obb : obbFiles) {
2548 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2549 obbDirName, obb.getAbsolutePath(), output);
2550 }
2551 }
2552 }
2553 }
2554
Christopher Tateb0628bf2011-06-02 15:08:13 -07002555 private void backupSharedStorage() throws RemoteException {
2556 PackageInfo pkg = null;
2557 try {
2558 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2559 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2560 IApplicationThread.BACKUP_MODE_FULL);
2561 if (agent != null) {
2562 sendOnBackupPackage("Shared storage");
2563
2564 final int token = generateToken();
Christopher Tate8e294d42011-08-31 20:37:12 -07002565 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL, null);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002566 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002567 if (!waitUntilOperationComplete(token)) {
2568 Slog.e(TAG, "Full backup failed on shared storage");
2569 } else {
2570 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2571 }
2572 } else {
2573 Slog.e(TAG, "Could not bind to shared storage backup agent");
2574 }
2575 } catch (NameNotFoundException e) {
2576 Slog.e(TAG, "Shared storage backup package not found");
2577 } finally {
2578 tearDown(pkg);
2579 }
2580 }
2581
Christopher Tate6853fcf2011-08-10 17:52:21 -07002582 private void finalizeBackup(OutputStream out) {
2583 try {
2584 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2585 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2586 out.write(eof);
2587 } catch (IOException e) {
2588 Slog.w(TAG, "Error attempting to finalize backup stream");
2589 }
2590 }
2591
Christopher Tate4a627c72011-04-01 14:43:32 -07002592 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2593 throws IOException {
2594 // Manifest format. All data are strings ending in LF:
2595 // BACKUP_MANIFEST_VERSION, currently 1
2596 //
2597 // Version 1:
2598 // package name
2599 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002600 // platform versionCode
2601 // getInstallerPackageName() for this package (maybe empty)
2602 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002603 // number of signatures == N
2604 // N*: signature byte array in ascii format per Signature.toCharsString()
2605 StringBuilder builder = new StringBuilder(4096);
2606 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2607
2608 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2609 printer.println(pkg.packageName);
2610 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002611 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2612
2613 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2614 printer.println((installerName != null) ? installerName : "");
2615
Christopher Tate4a627c72011-04-01 14:43:32 -07002616 printer.println(withApk ? "1" : "0");
2617 if (pkg.signatures == null) {
2618 printer.println("0");
2619 } else {
2620 printer.println(Integer.toString(pkg.signatures.length));
2621 for (Signature sig : pkg.signatures) {
2622 printer.println(sig.toCharsString());
2623 }
2624 }
2625
2626 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002627 outstream.write(builder.toString().getBytes());
2628 outstream.close();
2629 }
2630
2631 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002632 if (pkg != null) {
2633 final ApplicationInfo app = pkg.applicationInfo;
2634 if (app != null) {
2635 try {
2636 // unbind and tidy up even on timeout or failure, just in case
2637 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002638
Christopher Tateb0628bf2011-06-02 15:08:13 -07002639 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002640 if (app.uid != Process.SYSTEM_UID
2641 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002642 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002643 mActivityManager.killApplicationProcess(app.processName, app.uid);
2644 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002645 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002646 }
2647 } catch (RemoteException e) {
2648 Slog.d(TAG, "Lost app trying to shut down");
2649 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002650 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002651 }
2652 }
2653
2654 // wrappers for observer use
2655 void sendStartBackup() {
2656 if (mObserver != null) {
2657 try {
2658 mObserver.onStartBackup();
2659 } catch (RemoteException e) {
2660 Slog.w(TAG, "full backup observer went away: startBackup");
2661 mObserver = null;
2662 }
2663 }
2664 }
2665
2666 void sendOnBackupPackage(String name) {
2667 if (mObserver != null) {
2668 try {
2669 // TODO: use a more user-friendly name string
2670 mObserver.onBackupPackage(name);
2671 } catch (RemoteException e) {
2672 Slog.w(TAG, "full backup observer went away: backupPackage");
2673 mObserver = null;
2674 }
2675 }
2676 }
2677
2678 void sendEndBackup() {
2679 if (mObserver != null) {
2680 try {
2681 mObserver.onEndBackup();
2682 } catch (RemoteException e) {
2683 Slog.w(TAG, "full backup observer went away: endBackup");
2684 mObserver = null;
2685 }
2686 }
2687 }
2688 }
2689
2690
Christopher Tate75a99702011-05-18 16:28:19 -07002691 // ----- Full restore from a file/socket -----
2692
2693 // Description of a file in the restore datastream
2694 static class FileMetadata {
2695 String packageName; // name of the owning app
2696 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002697 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002698 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2699 String path; // subpath within the semantic domain
2700 long mode; // e.g. 0666 (actually int)
2701 long mtime; // last mod time, UTC time_t (actually int)
2702 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002703
2704 @Override
2705 public String toString() {
2706 StringBuilder sb = new StringBuilder(128);
2707 sb.append("FileMetadata{");
2708 sb.append(packageName); sb.append(',');
2709 sb.append(type); sb.append(',');
2710 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2711 sb.append(size);
2712 sb.append('}');
2713 return sb.toString();
2714 }
Christopher Tate75a99702011-05-18 16:28:19 -07002715 }
2716
2717 enum RestorePolicy {
2718 IGNORE,
2719 ACCEPT,
2720 ACCEPT_IF_APK
2721 }
2722
2723 class PerformFullRestoreTask implements Runnable {
2724 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002725 String mCurrentPassword;
2726 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002727 IFullBackupRestoreObserver mObserver;
2728 AtomicBoolean mLatchObject;
2729 IBackupAgent mAgent;
2730 String mAgentPackage;
2731 ApplicationInfo mTargetApp;
2732 ParcelFileDescriptor[] mPipes = null;
2733
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002734 long mBytes;
2735
Christopher Tate75a99702011-05-18 16:28:19 -07002736 // possible handling states for a given package in the restore dataset
2737 final HashMap<String, RestorePolicy> mPackagePolicies
2738 = new HashMap<String, RestorePolicy>();
2739
2740 // installer package names for each encountered app, derived from the manifests
2741 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2742
2743 // Signatures for a given package found in its manifest file
2744 final HashMap<String, Signature[]> mManifestSignatures
2745 = new HashMap<String, Signature[]>();
2746
2747 // Packages we've already wiped data on when restoring their first file
2748 final HashSet<String> mClearedPackages = new HashSet<String>();
2749
Christopher Tate728a1c42011-07-28 18:03:03 -07002750 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002751 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002752 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002753 mCurrentPassword = curPassword;
2754 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002755 mObserver = observer;
2756 mLatchObject = latch;
2757 mAgent = null;
2758 mAgentPackage = null;
2759 mTargetApp = null;
2760
2761 // Which packages we've already wiped data on. We prepopulate this
2762 // with a whitelist of packages known to be unclearable.
2763 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002764 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002765
Christopher Tate75a99702011-05-18 16:28:19 -07002766 }
2767
2768 class RestoreFileRunnable implements Runnable {
2769 IBackupAgent mAgent;
2770 FileMetadata mInfo;
2771 ParcelFileDescriptor mSocket;
2772 int mToken;
2773
2774 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2775 ParcelFileDescriptor socket, int token) throws IOException {
2776 mAgent = agent;
2777 mInfo = info;
2778 mToken = token;
2779
2780 // This class is used strictly for process-local binder invocations. The
2781 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2782 // do not automatically get a 'dup'ed descriptor that we can can continue
2783 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2784 // before proceeding to do the restore.
2785 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2786 }
2787
2788 @Override
2789 public void run() {
2790 try {
2791 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2792 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2793 mToken, mBackupManagerBinder);
2794 } catch (RemoteException e) {
2795 // never happens; this is used strictly for local binder calls
2796 }
2797 }
2798 }
2799
2800 @Override
2801 public void run() {
2802 Slog.i(TAG, "--- Performing full-dataset restore ---");
2803 sendStartRestore();
2804
Christopher Tateb0628bf2011-06-02 15:08:13 -07002805 // Are we able to restore shared-storage data?
2806 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2807 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2808 }
2809
Christopher Tate2efd2db2011-07-19 16:32:49 -07002810 FileInputStream rawInStream = null;
2811 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002812 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002813 if (hasBackupPassword()) {
2814 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2815 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2816 return;
2817 }
2818 }
2819
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002820 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002821 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002822 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2823 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002824
2825 // First, parse out the unencrypted/uncompressed header
2826 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002827 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002828 final InputStream in;
2829
2830 boolean okay = false;
2831 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2832 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002833 rawDataIn.readFully(streamHeader);
2834 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2835 if (Arrays.equals(magicBytes, streamHeader)) {
2836 // okay, header looks good. now parse out the rest of the fields.
2837 String s = readHeaderLine(rawInStream);
2838 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2839 // okay, it's a version we recognize
2840 s = readHeaderLine(rawInStream);
2841 compressed = (Integer.parseInt(s) != 0);
2842 s = readHeaderLine(rawInStream);
2843 if (s.equals("none")) {
2844 // no more header to parse; we're good to go
2845 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002846 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002847 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2848 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002849 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002850 }
2851 } else Slog.w(TAG, "Archive is encrypted but no password given");
2852 } else Slog.w(TAG, "Wrong header version: " + s);
2853 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002854
2855 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002856 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002857 return;
2858 }
2859
2860 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002861 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002862
2863 boolean didRestore;
2864 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002865 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002866 } while (didRestore);
2867
Christopher Tatec58efa62011-08-01 19:20:14 -07002868 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002869 } catch (IOException e) {
2870 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002871 } finally {
2872 tearDownPipes();
2873 tearDownAgent(mTargetApp);
2874
2875 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002876 if (rawDataIn != null) rawDataIn.close();
2877 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002878 mInputFile.close();
2879 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002880 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002881 /* nothing we can do about this */
2882 }
2883 synchronized (mCurrentOpLock) {
2884 mCurrentOperations.clear();
2885 }
2886 synchronized (mLatchObject) {
2887 mLatchObject.set(true);
2888 mLatchObject.notifyAll();
2889 }
2890 sendEndRestore();
2891 mWakelock.release();
Christopher Tatec58efa62011-08-01 19:20:14 -07002892 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07002893 }
2894 }
2895
Christopher Tate7bdb0962011-07-13 19:30:21 -07002896 String readHeaderLine(InputStream in) throws IOException {
2897 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002898 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002899 while ((c = in.read()) >= 0) {
2900 if (c == '\n') break; // consume and discard the newlines
2901 buffer.append((char)c);
2902 }
2903 return buffer.toString();
2904 }
2905
Christopher Tate2efd2db2011-07-19 16:32:49 -07002906 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2907 InputStream result = null;
2908 try {
2909 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2910
2911 String userSaltHex = readHeaderLine(rawInStream); // 5
2912 byte[] userSalt = hexToByteArray(userSaltHex);
2913
2914 String ckSaltHex = readHeaderLine(rawInStream); // 6
2915 byte[] ckSalt = hexToByteArray(ckSaltHex);
2916
2917 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2918 String userIvHex = readHeaderLine(rawInStream); // 8
2919
2920 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2921
2922 // decrypt the master key blob
2923 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002924 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002925 rounds);
2926 byte[] IV = hexToByteArray(userIvHex);
2927 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2928 c.init(Cipher.DECRYPT_MODE,
2929 new SecretKeySpec(userKey.getEncoded(), "AES"),
2930 ivSpec);
2931 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2932 byte[] mkBlob = c.doFinal(mkCipher);
2933
2934 // first, the master key IV
2935 int offset = 0;
2936 int len = mkBlob[offset++];
2937 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2938 offset += len;
2939 // then the master key itself
2940 len = mkBlob[offset++];
2941 byte[] mk = Arrays.copyOfRange(mkBlob,
2942 offset, offset + len);
2943 offset += len;
2944 // and finally the master key checksum hash
2945 len = mkBlob[offset++];
2946 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2947 offset, offset + len);
2948
2949 // now validate the decrypted master key against the checksum
2950 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2951 if (Arrays.equals(calculatedCk, mkChecksum)) {
2952 ivSpec = new IvParameterSpec(IV);
2953 c.init(Cipher.DECRYPT_MODE,
2954 new SecretKeySpec(mk, "AES"),
2955 ivSpec);
2956 // Only if all of the above worked properly will 'result' be assigned
2957 result = new CipherInputStream(rawInStream, c);
2958 } else Slog.w(TAG, "Incorrect password");
2959 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2960 } catch (InvalidAlgorithmParameterException e) {
2961 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2962 } catch (BadPaddingException e) {
2963 // This case frequently occurs when the wrong password is used to decrypt
2964 // the master key. Use the identical "incorrect password" log text as is
2965 // used in the checksum failure log in order to avoid providing additional
2966 // information to an attacker.
2967 Slog.w(TAG, "Incorrect password");
2968 } catch (IllegalBlockSizeException e) {
2969 Slog.w(TAG, "Invalid block size in master key");
2970 } catch (NoSuchAlgorithmException e) {
2971 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2972 } catch (NoSuchPaddingException e) {
2973 Slog.e(TAG, "Needed padding mechanism unavailable!");
2974 } catch (InvalidKeyException e) {
2975 Slog.w(TAG, "Illegal password; aborting");
2976 } catch (NumberFormatException e) {
2977 Slog.w(TAG, "Can't parse restore data header");
2978 } catch (IOException e) {
2979 Slog.w(TAG, "Can't read input header");
2980 }
2981
2982 return result;
2983 }
2984
Christopher Tate75a99702011-05-18 16:28:19 -07002985 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2986 FileMetadata info;
2987 try {
2988 info = readTarHeaders(instream);
2989 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002990 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07002991 dumpFileMetadata(info);
2992 }
2993
2994 final String pkg = info.packageName;
2995 if (!pkg.equals(mAgentPackage)) {
2996 // okay, change in package; set up our various
2997 // bookkeeping if we haven't seen it yet
2998 if (!mPackagePolicies.containsKey(pkg)) {
2999 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3000 }
3001
3002 // Clean up the previous agent relationship if necessary,
3003 // and let the observer know we're considering a new app.
3004 if (mAgent != null) {
3005 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
3006 tearDownPipes();
3007 tearDownAgent(mTargetApp);
3008 mTargetApp = null;
3009 mAgentPackage = null;
3010 }
3011 }
3012
3013 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3014 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3015 mPackageInstallers.put(pkg, info.installerPackageName);
3016 // We've read only the manifest content itself at this point,
3017 // so consume the footer before looping around to the next
3018 // input file
3019 skipTarPadding(info.size, instream);
3020 sendOnRestorePackage(pkg);
3021 } else {
3022 // Non-manifest, so it's actual file data. Is this a package
3023 // we're ignoring?
3024 boolean okay = true;
3025 RestorePolicy policy = mPackagePolicies.get(pkg);
3026 switch (policy) {
3027 case IGNORE:
3028 okay = false;
3029 break;
3030
3031 case ACCEPT_IF_APK:
3032 // If we're in accept-if-apk state, then the first file we
3033 // see MUST be the apk.
3034 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3035 if (DEBUG) Slog.d(TAG, "APK file; installing");
3036 // Try to install the app.
3037 String installerName = mPackageInstallers.get(pkg);
3038 okay = installApk(info, installerName, instream);
3039 // good to go; promote to ACCEPT
3040 mPackagePolicies.put(pkg, (okay)
3041 ? RestorePolicy.ACCEPT
3042 : RestorePolicy.IGNORE);
3043 // At this point we've consumed this file entry
3044 // ourselves, so just strip the tar footer and
3045 // go on to the next file in the input stream
3046 skipTarPadding(info.size, instream);
3047 return true;
3048 } else {
3049 // File data before (or without) the apk. We can't
3050 // handle it coherently in this case so ignore it.
3051 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3052 okay = false;
3053 }
3054 break;
3055
3056 case ACCEPT:
3057 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3058 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3059 // we can take the data without the apk, so we
3060 // *want* to do so. skip the apk by declaring this
3061 // one file not-okay without changing the restore
3062 // policy for the package.
3063 okay = false;
3064 }
3065 break;
3066
3067 default:
3068 // Something has gone dreadfully wrong when determining
3069 // the restore policy from the manifest. Ignore the
3070 // rest of this package's data.
3071 Slog.e(TAG, "Invalid policy from manifest");
3072 okay = false;
3073 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3074 break;
3075 }
3076
3077 // If the policy is satisfied, go ahead and set up to pipe the
3078 // data to the agent.
3079 if (DEBUG && okay && mAgent != null) {
3080 Slog.i(TAG, "Reusing existing agent instance");
3081 }
3082 if (okay && mAgent == null) {
3083 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3084
3085 try {
3086 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3087
3088 // If we haven't sent any data to this app yet, we probably
3089 // need to clear it first. Check that.
3090 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003091 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003092 // responsible for coherently managing a full
3093 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003094 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003095 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3096 clearApplicationDataSynchronous(pkg);
3097 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003098 if (DEBUG) Slog.d(TAG, "backup agent ("
3099 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003100 }
3101 mClearedPackages.add(pkg);
3102 } else {
3103 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3104 }
3105
3106 // All set; now set up the IPC and launch the agent
3107 setUpPipes();
3108 mAgent = bindToAgentSynchronous(mTargetApp,
3109 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3110 mAgentPackage = pkg;
3111 } catch (IOException e) {
3112 // fall through to error handling
3113 } catch (NameNotFoundException e) {
3114 // fall through to error handling
3115 }
3116
3117 if (mAgent == null) {
3118 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3119 okay = false;
3120 tearDownPipes();
3121 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3122 }
3123 }
3124
3125 // Sanity check: make sure we never give data to the wrong app. This
3126 // should never happen but a little paranoia here won't go amiss.
3127 if (okay && !pkg.equals(mAgentPackage)) {
3128 Slog.e(TAG, "Restoring data for " + pkg
3129 + " but agent is for " + mAgentPackage);
3130 okay = false;
3131 }
3132
3133 // At this point we have an agent ready to handle the full
3134 // restore data as well as a pipe for sending data to
3135 // that agent. Tell the agent to start reading from the
3136 // pipe.
3137 if (okay) {
3138 boolean agentSuccess = true;
3139 long toCopy = info.size;
3140 final int token = generateToken();
3141 try {
3142 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3143 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003144 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003145 // fire up the app's agent listening on the socket. If
3146 // the agent is running in the system process we can't
3147 // just invoke it asynchronously, so we provide a thread
3148 // for it here.
3149 if (mTargetApp.processName.equals("system")) {
3150 Slog.d(TAG, "system process agent - spinning a thread");
3151 RestoreFileRunnable runner = new RestoreFileRunnable(
3152 mAgent, info, mPipes[0], token);
3153 new Thread(runner).start();
3154 } else {
3155 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3156 info.domain, info.path, info.mode, info.mtime,
3157 token, mBackupManagerBinder);
3158 }
3159 } catch (IOException e) {
3160 // couldn't dup the socket for a process-local restore
3161 Slog.d(TAG, "Couldn't establish restore");
3162 agentSuccess = false;
3163 okay = false;
3164 } catch (RemoteException e) {
3165 // whoops, remote agent went away. We'll eat the content
3166 // ourselves, then, and not copy it over.
3167 Slog.e(TAG, "Agent crashed during full restore");
3168 agentSuccess = false;
3169 okay = false;
3170 }
3171
3172 // Copy over the data if the agent is still good
3173 if (okay) {
3174 boolean pipeOkay = true;
3175 FileOutputStream pipe = new FileOutputStream(
3176 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003177 while (toCopy > 0) {
3178 int toRead = (toCopy > buffer.length)
3179 ? buffer.length : (int)toCopy;
3180 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003181 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003182 if (nRead <= 0) break;
3183 toCopy -= nRead;
3184
3185 // send it to the output pipe as long as things
3186 // are still good
3187 if (pipeOkay) {
3188 try {
3189 pipe.write(buffer, 0, nRead);
3190 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003191 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003192 pipeOkay = false;
3193 }
3194 }
3195 }
3196
3197 // done sending that file! Now we just need to consume
3198 // the delta from info.size to the end of block.
3199 skipTarPadding(info.size, instream);
3200
3201 // and now that we've sent it all, wait for the remote
3202 // side to acknowledge receipt
3203 agentSuccess = waitUntilOperationComplete(token);
3204 }
3205
3206 // okay, if the remote end failed at any point, deal with
3207 // it by ignoring the rest of the restore on it
3208 if (!agentSuccess) {
3209 mBackupHandler.removeMessages(MSG_TIMEOUT);
3210 tearDownPipes();
3211 tearDownAgent(mTargetApp);
3212 mAgent = null;
3213 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3214 }
3215 }
3216
3217 // Problems setting up the agent communication, or an already-
3218 // ignored package: skip to the next tar stream entry by
3219 // reading and discarding this file.
3220 if (!okay) {
3221 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3222 long bytesToConsume = (info.size + 511) & ~511;
3223 while (bytesToConsume > 0) {
3224 int toRead = (bytesToConsume > buffer.length)
3225 ? buffer.length : (int)bytesToConsume;
3226 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003227 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003228 if (nRead <= 0) break;
3229 bytesToConsume -= nRead;
3230 }
3231 }
3232 }
3233 }
3234 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003235 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003236 // treat as EOF
3237 info = null;
3238 }
3239
3240 return (info != null);
3241 }
3242
3243 void setUpPipes() throws IOException {
3244 mPipes = ParcelFileDescriptor.createPipe();
3245 }
3246
3247 void tearDownPipes() {
3248 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003249 try {
3250 mPipes[0].close();
3251 mPipes[0] = null;
3252 mPipes[1].close();
3253 mPipes[1] = null;
3254 } catch (IOException e) {
3255 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003256 }
3257 mPipes = null;
3258 }
3259 }
3260
3261 void tearDownAgent(ApplicationInfo app) {
3262 if (mAgent != null) {
3263 try {
3264 // unbind and tidy up even on timeout or failure, just in case
3265 mActivityManager.unbindBackupAgent(app);
3266
3267 // The agent was running with a stub Application object, so shut it down.
3268 // !!! We hardcode the confirmation UI's package name here rather than use a
3269 // manifest flag! TODO something less direct.
3270 if (app.uid != Process.SYSTEM_UID
3271 && !app.packageName.equals("com.android.backupconfirm")) {
3272 if (DEBUG) Slog.d(TAG, "Killing host process");
3273 mActivityManager.killApplicationProcess(app.processName, app.uid);
3274 } else {
3275 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3276 }
3277 } catch (RemoteException e) {
3278 Slog.d(TAG, "Lost app trying to shut down");
3279 }
3280 mAgent = null;
3281 }
3282 }
3283
3284 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3285 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003286 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003287 int mResult;
3288
3289 public void reset() {
3290 synchronized (mDone) {
3291 mDone.set(false);
3292 }
3293 }
3294
3295 public void waitForCompletion() {
3296 synchronized (mDone) {
3297 while (mDone.get() == false) {
3298 try {
3299 mDone.wait();
3300 } catch (InterruptedException e) { }
3301 }
3302 }
3303 }
3304
3305 int getResult() {
3306 return mResult;
3307 }
3308
3309 @Override
3310 public void packageInstalled(String packageName, int returnCode)
3311 throws RemoteException {
3312 synchronized (mDone) {
3313 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003314 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003315 mDone.set(true);
3316 mDone.notifyAll();
3317 }
3318 }
3319 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003320
3321 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3322 final AtomicBoolean mDone = new AtomicBoolean();
3323 int mResult;
3324
3325 public void reset() {
3326 synchronized (mDone) {
3327 mDone.set(false);
3328 }
3329 }
3330
3331 public void waitForCompletion() {
3332 synchronized (mDone) {
3333 while (mDone.get() == false) {
3334 try {
3335 mDone.wait();
3336 } catch (InterruptedException e) { }
3337 }
3338 }
3339 }
3340
3341 @Override
3342 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3343 synchronized (mDone) {
3344 mResult = returnCode;
3345 mDone.set(true);
3346 mDone.notifyAll();
3347 }
3348 }
3349 }
3350
Christopher Tate75a99702011-05-18 16:28:19 -07003351 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003352 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003353
3354 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3355 boolean okay = true;
3356
3357 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3358
3359 // The file content is an .apk file. Copy it out to a staging location and
3360 // attempt to install it.
3361 File apkFile = new File(mDataDir, info.packageName);
3362 try {
3363 FileOutputStream apkStream = new FileOutputStream(apkFile);
3364 byte[] buffer = new byte[32 * 1024];
3365 long size = info.size;
3366 while (size > 0) {
3367 long toRead = (buffer.length < size) ? buffer.length : size;
3368 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003369 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003370 apkStream.write(buffer, 0, didRead);
3371 size -= didRead;
3372 }
3373 apkStream.close();
3374
3375 // make sure the installer can read it
3376 apkFile.setReadable(true, false);
3377
3378 // Now install it
3379 Uri packageUri = Uri.fromFile(apkFile);
3380 mInstallObserver.reset();
3381 mPackageManager.installPackage(packageUri, mInstallObserver,
3382 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
3383 mInstallObserver.waitForCompletion();
3384
3385 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3386 // The only time we continue to accept install of data even if the
3387 // apk install failed is if we had already determined that we could
3388 // accept the data regardless.
3389 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3390 okay = false;
3391 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003392 } else {
3393 // Okay, the install succeeded. Make sure it was the right app.
3394 boolean uninstall = false;
3395 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3396 Slog.w(TAG, "Restore stream claimed to include apk for "
3397 + info.packageName + " but apk was really "
3398 + mInstallObserver.mPackageName);
3399 // delete the package we just put in place; it might be fraudulent
3400 okay = false;
3401 uninstall = true;
3402 } else {
3403 try {
3404 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3405 PackageManager.GET_SIGNATURES);
3406 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3407 Slog.w(TAG, "Restore stream contains apk of package "
3408 + info.packageName + " but it disallows backup/restore");
3409 okay = false;
3410 } else {
3411 // So far so good -- do the signatures match the manifest?
3412 Signature[] sigs = mManifestSignatures.get(info.packageName);
3413 if (!signaturesMatch(sigs, pkg)) {
3414 Slog.w(TAG, "Installed app " + info.packageName
3415 + " signatures do not match restore manifest");
3416 okay = false;
3417 uninstall = true;
3418 }
3419 }
3420 } catch (NameNotFoundException e) {
3421 Slog.w(TAG, "Install of package " + info.packageName
3422 + " succeeded but now not found");
3423 okay = false;
3424 }
3425 }
3426
3427 // If we're not okay at this point, we need to delete the package
3428 // that we just installed.
3429 if (uninstall) {
3430 mDeleteObserver.reset();
3431 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3432 mDeleteObserver, 0);
3433 mDeleteObserver.waitForCompletion();
3434 }
Christopher Tate75a99702011-05-18 16:28:19 -07003435 }
3436 } catch (IOException e) {
3437 Slog.e(TAG, "Unable to transcribe restored apk for install");
3438 okay = false;
3439 } finally {
3440 apkFile.delete();
3441 }
3442
3443 return okay;
3444 }
3445
3446 // Given an actual file content size, consume the post-content padding mandated
3447 // by the tar format.
3448 void skipTarPadding(long size, InputStream instream) throws IOException {
3449 long partial = (size + 512) % 512;
3450 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003451 final int needed = 512 - (int)partial;
3452 byte[] buffer = new byte[needed];
3453 if (readExactly(instream, buffer, 0, needed) == needed) {
3454 mBytes += needed;
3455 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003456 }
3457 }
3458
3459 // Returns a policy constant; takes a buffer arg to reduce memory churn
3460 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3461 throws IOException {
3462 // Fail on suspiciously large manifest files
3463 if (info.size > 64 * 1024) {
3464 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3465 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003466
Christopher Tate75a99702011-05-18 16:28:19 -07003467 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003468 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3469 mBytes += info.size;
3470 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003471
3472 RestorePolicy policy = RestorePolicy.IGNORE;
3473 String[] str = new String[1];
3474 int offset = 0;
3475
3476 try {
3477 offset = extractLine(buffer, offset, str);
3478 int version = Integer.parseInt(str[0]);
3479 if (version == BACKUP_MANIFEST_VERSION) {
3480 offset = extractLine(buffer, offset, str);
3481 String manifestPackage = str[0];
3482 // TODO: handle <original-package>
3483 if (manifestPackage.equals(info.packageName)) {
3484 offset = extractLine(buffer, offset, str);
3485 version = Integer.parseInt(str[0]); // app version
3486 offset = extractLine(buffer, offset, str);
3487 int platformVersion = Integer.parseInt(str[0]);
3488 offset = extractLine(buffer, offset, str);
3489 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3490 offset = extractLine(buffer, offset, str);
3491 boolean hasApk = str[0].equals("1");
3492 offset = extractLine(buffer, offset, str);
3493 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003494 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003495 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003496 for (int i = 0; i < numSigs; i++) {
3497 offset = extractLine(buffer, offset, str);
3498 sigs[i] = new Signature(str[0]);
3499 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003500 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003501
3502 // Okay, got the manifest info we need...
3503 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003504 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3505 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003506 // Fall through to IGNORE if the app explicitly disallows backup
3507 final int flags = pkgInfo.applicationInfo.flags;
3508 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3509 // Verify signatures against any installed version; if they
3510 // don't match, then we fall though and ignore the data. The
3511 // signatureMatch() method explicitly ignores the signature
3512 // check for packages installed on the system partition, because
3513 // such packages are signed with the platform cert instead of
3514 // the app developer's cert, so they're different on every
3515 // device.
3516 if (signaturesMatch(sigs, pkgInfo)) {
3517 if (pkgInfo.versionCode >= version) {
3518 Slog.i(TAG, "Sig + version match; taking data");
3519 policy = RestorePolicy.ACCEPT;
3520 } else {
3521 // The data is from a newer version of the app than
3522 // is presently installed. That means we can only
3523 // use it if the matching apk is also supplied.
3524 Slog.d(TAG, "Data version " + version
3525 + " is newer than installed version "
3526 + pkgInfo.versionCode + " - requiring apk");
3527 policy = RestorePolicy.ACCEPT_IF_APK;
3528 }
Christopher Tate75a99702011-05-18 16:28:19 -07003529 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003530 Slog.w(TAG, "Restore manifest signatures do not match "
3531 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003532 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003533 } else {
3534 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3535 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003536 }
3537 } catch (NameNotFoundException e) {
3538 // Okay, the target app isn't installed. We can process
3539 // the restore properly only if the dataset provides the
3540 // apk file and we can successfully install it.
3541 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3542 + " not installed; requiring apk in dataset");
3543 policy = RestorePolicy.ACCEPT_IF_APK;
3544 }
3545
3546 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3547 Slog.i(TAG, "Cannot restore package " + info.packageName
3548 + " without the matching .apk");
3549 }
3550 } else {
3551 Slog.i(TAG, "Missing signature on backed-up package "
3552 + info.packageName);
3553 }
3554 } else {
3555 Slog.i(TAG, "Expected package " + info.packageName
3556 + " but restore manifest claims " + manifestPackage);
3557 }
3558 } else {
3559 Slog.i(TAG, "Unknown restore manifest version " + version
3560 + " for package " + info.packageName);
3561 }
3562 } catch (NumberFormatException e) {
3563 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003564 } catch (IllegalArgumentException e) {
3565 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003566 }
3567
3568 return policy;
3569 }
3570
3571 // Builds a line from a byte buffer starting at 'offset', and returns
3572 // the index of the next unconsumed data in the buffer.
3573 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3574 final int end = buffer.length;
3575 if (offset >= end) throw new IOException("Incomplete data");
3576
3577 int pos;
3578 for (pos = offset; pos < end; pos++) {
3579 byte c = buffer[pos];
3580 // at LF we declare end of line, and return the next char as the
3581 // starting point for the next time through
3582 if (c == '\n') {
3583 break;
3584 }
3585 }
3586 outStr[0] = new String(buffer, offset, pos - offset);
3587 pos++; // may be pointing an extra byte past the end but that's okay
3588 return pos;
3589 }
3590
3591 void dumpFileMetadata(FileMetadata info) {
3592 if (DEBUG) {
3593 StringBuilder b = new StringBuilder(128);
3594
3595 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003596 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003597 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3598 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3599 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3600 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3601 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3602 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3603 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3604 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3605 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3606 b.append(String.format(" %9d ", info.size));
3607
3608 Date stamp = new Date(info.mtime);
3609 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3610
3611 b.append(info.packageName);
3612 b.append(" :: ");
3613 b.append(info.domain);
3614 b.append(" :: ");
3615 b.append(info.path);
3616
3617 Slog.i(TAG, b.toString());
3618 }
3619 }
3620 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3621 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3622 byte[] block = new byte[512];
3623 FileMetadata info = null;
3624
3625 boolean gotHeader = readTarHeader(instream, block);
3626 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003627 try {
3628 // okay, presume we're okay, and extract the various metadata
3629 info = new FileMetadata();
3630 info.size = extractRadix(block, 124, 12, 8);
3631 info.mtime = extractRadix(block, 136, 12, 8);
3632 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003633
Christopher Tate2efd2db2011-07-19 16:32:49 -07003634 info.path = extractString(block, 345, 155); // prefix
3635 String path = extractString(block, 0, 100);
3636 if (path.length() > 0) {
3637 if (info.path.length() > 0) info.path += '/';
3638 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003639 }
Christopher Tate75a99702011-05-18 16:28:19 -07003640
Christopher Tate2efd2db2011-07-19 16:32:49 -07003641 // tar link indicator field: 1 byte at offset 156 in the header.
3642 int typeChar = block[156];
3643 if (typeChar == 'x') {
3644 // pax extended header, so we need to read that
3645 gotHeader = readPaxExtendedHeader(instream, info);
3646 if (gotHeader) {
3647 // and after a pax extended header comes another real header -- read
3648 // that to find the real file type
3649 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003650 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003651 if (!gotHeader) throw new IOException("Bad or missing pax header");
3652
3653 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003654 }
Christopher Tate75a99702011-05-18 16:28:19 -07003655
Christopher Tate2efd2db2011-07-19 16:32:49 -07003656 switch (typeChar) {
3657 case '0': info.type = BackupAgent.TYPE_FILE; break;
3658 case '5': {
3659 info.type = BackupAgent.TYPE_DIRECTORY;
3660 if (info.size != 0) {
3661 Slog.w(TAG, "Directory entry with nonzero size in header");
3662 info.size = 0;
3663 }
3664 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003665 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003666 case 0: {
3667 // presume EOF
3668 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3669 return null;
3670 }
3671 default: {
3672 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3673 throw new IOException("Unknown entity type " + typeChar);
3674 }
Christopher Tate75a99702011-05-18 16:28:19 -07003675 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003676
3677 // Parse out the path
3678 //
3679 // first: apps/shared/unrecognized
3680 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3681 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3682 // File in shared storage. !!! TODO: implement this.
3683 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3684 info.packageName = "com.android.sharedstoragebackup";
3685 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3686 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3687 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3688 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3689 // App content! Parse out the package name and domain
3690
3691 // strip the apps/ prefix
3692 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3693
3694 // extract the package name
3695 int slash = info.path.indexOf('/');
3696 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3697 info.packageName = info.path.substring(0, slash);
3698 info.path = info.path.substring(slash+1);
3699
3700 // if it's a manifest we're done, otherwise parse out the domains
3701 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3702 slash = info.path.indexOf('/');
3703 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3704 info.domain = info.path.substring(0, slash);
3705 // validate that it's one of the domains we understand
3706 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3707 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3708 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3709 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3710 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3711 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3712 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3713 throw new IOException("Unrecognized domain " + info.domain);
3714 }
3715
3716 info.path = info.path.substring(slash + 1);
3717 }
3718 }
3719 } catch (IOException e) {
3720 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003721 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003722 HEXLOG(block);
3723 }
3724 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003725 }
3726 }
3727 return info;
3728 }
3729
Christopher Tate2efd2db2011-07-19 16:32:49 -07003730 private void HEXLOG(byte[] block) {
3731 int offset = 0;
3732 int todo = block.length;
3733 StringBuilder buf = new StringBuilder(64);
3734 while (todo > 0) {
3735 buf.append(String.format("%04x ", offset));
3736 int numThisLine = (todo > 16) ? 16 : todo;
3737 for (int i = 0; i < numThisLine; i++) {
3738 buf.append(String.format("%02x ", block[offset+i]));
3739 }
3740 Slog.i("hexdump", buf.toString());
3741 buf.setLength(0);
3742 todo -= numThisLine;
3743 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003744 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003745 }
3746
Christopher Tate6853fcf2011-08-10 17:52:21 -07003747 // Read exactly the given number of bytes into a buffer at the stated offset.
3748 // Returns false if EOF is encountered before the requested number of bytes
3749 // could be read.
3750 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3751 throws IOException {
3752 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3753
3754 int soFar = 0;
3755 while (soFar < size) {
3756 int nRead = in.read(buffer, offset + soFar, size - soFar);
3757 if (nRead <= 0) {
3758 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3759 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003760 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003761 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003762 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003763 return soFar;
3764 }
3765
3766 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3767 final int got = readExactly(instream, block, 0, 512);
3768 if (got == 0) return false; // Clean EOF
3769 if (got < 512) throw new IOException("Unable to read full block header");
3770 mBytes += 512;
3771 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003772 }
3773
3774 // overwrites 'info' fields based on the pax extended header
3775 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3776 throws IOException {
3777 // We should never see a pax extended header larger than this
3778 if (info.size > 32*1024) {
3779 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3780 + " - aborting");
3781 throw new IOException("Sanity failure: pax header size " + info.size);
3782 }
3783
3784 // read whole blocks, not just the content size
3785 int numBlocks = (int)((info.size + 511) >> 9);
3786 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003787 if (readExactly(instream, data, 0, data.length) < data.length) {
3788 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003789 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003790 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003791
3792 final int contentSize = (int) info.size;
3793 int offset = 0;
3794 do {
3795 // extract the line at 'offset'
3796 int eol = offset+1;
3797 while (eol < contentSize && data[eol] != ' ') eol++;
3798 if (eol >= contentSize) {
3799 // error: we just hit EOD looking for the end of the size field
3800 throw new IOException("Invalid pax data");
3801 }
3802 // eol points to the space between the count and the key
3803 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3804 int key = eol + 1; // start of key=value
3805 eol = offset + linelen - 1; // trailing LF
3806 int value;
3807 for (value = key+1; data[value] != '=' && value <= eol; value++);
3808 if (value > eol) {
3809 throw new IOException("Invalid pax declaration");
3810 }
3811
3812 // pax requires that key/value strings be in UTF-8
3813 String keyStr = new String(data, key, value-key, "UTF-8");
3814 // -1 to strip the trailing LF
3815 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3816
3817 if ("path".equals(keyStr)) {
3818 info.path = valStr;
3819 } else if ("size".equals(keyStr)) {
3820 info.size = Long.parseLong(valStr);
3821 } else {
3822 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3823 }
3824
3825 offset += linelen;
3826 } while (offset < contentSize);
3827
3828 return true;
3829 }
3830
3831 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3832 throws IOException {
3833 long value = 0;
3834 final int end = offset + maxChars;
3835 for (int i = offset; i < end; i++) {
3836 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003837 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003838 if (b == 0 || b == ' ') break;
3839 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003840 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003841 }
3842 value = radix * value + (b - '0');
3843 }
3844 return value;
3845 }
3846
3847 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3848 final int end = offset + maxChars;
3849 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003850 // tar string fields terminate early with a NUL
3851 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003852 return new String(data, offset, eos-offset, "US-ASCII");
3853 }
3854
3855 void sendStartRestore() {
3856 if (mObserver != null) {
3857 try {
3858 mObserver.onStartRestore();
3859 } catch (RemoteException e) {
3860 Slog.w(TAG, "full restore observer went away: startRestore");
3861 mObserver = null;
3862 }
3863 }
3864 }
3865
3866 void sendOnRestorePackage(String name) {
3867 if (mObserver != null) {
3868 try {
3869 // TODO: use a more user-friendly name string
3870 mObserver.onRestorePackage(name);
3871 } catch (RemoteException e) {
3872 Slog.w(TAG, "full restore observer went away: restorePackage");
3873 mObserver = null;
3874 }
3875 }
3876 }
3877
3878 void sendEndRestore() {
3879 if (mObserver != null) {
3880 try {
3881 mObserver.onEndRestore();
3882 } catch (RemoteException e) {
3883 Slog.w(TAG, "full restore observer went away: endRestore");
3884 mObserver = null;
3885 }
3886 }
3887 }
3888 }
3889
Christopher Tatedf01dea2009-06-09 20:45:02 -07003890 // ----- Restore handling -----
3891
Christopher Tate78dd4a72009-11-04 11:49:08 -08003892 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3893 // If the target resides on the system partition, we allow it to restore
3894 // data from the like-named package in a restore set even if the signatures
3895 // do not match. (Unlike general applications, those flashed to the system
3896 // partition will be signed with the device's platform certificate, so on
3897 // different phones the same system app will have different signatures.)
3898 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003899 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003900 return true;
3901 }
3902
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003903 // Allow unsigned apps, but not signed on one device and unsigned on the other
3904 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003905 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003906 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003907 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003908 if ((storedSigs == null || storedSigs.length == 0)
3909 && (deviceSigs == null || deviceSigs.length == 0)) {
3910 return true;
3911 }
3912 if (storedSigs == null || deviceSigs == null) {
3913 return false;
3914 }
3915
Christopher Tateabce4e82009-06-18 18:35:32 -07003916 // !!! TODO: this demands that every stored signature match one
3917 // that is present on device, and does not demand the converse.
3918 // Is this this right policy?
3919 int nStored = storedSigs.length;
3920 int nDevice = deviceSigs.length;
3921
3922 for (int i=0; i < nStored; i++) {
3923 boolean match = false;
3924 for (int j=0; j < nDevice; j++) {
3925 if (storedSigs[i].equals(deviceSigs[j])) {
3926 match = true;
3927 break;
3928 }
3929 }
3930 if (!match) {
3931 return false;
3932 }
3933 }
3934 return true;
3935 }
3936
Christopher Tate2982d062011-09-06 20:35:24 -07003937 enum RestoreState {
3938 INITIAL,
3939 DOWNLOAD_DATA,
3940 PM_METADATA,
3941 RUNNING_QUEUE,
3942 FINAL
3943 }
3944
3945 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003946 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003947 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003948 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003949 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003950 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003951 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003952 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003953 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07003954 private long mStartRealtime;
3955 private PackageManagerBackupAgent mPmAgent;
3956 private List<PackageInfo> mAgentPackages;
3957 private ArrayList<PackageInfo> mRestorePackages;
3958 private RestoreState mCurrentState;
3959 private int mCount;
3960 private boolean mFinished;
3961 private int mStatus;
3962 private File mBackupDataName;
3963 private File mNewStateName;
3964 private File mSavedStateName;
3965 private ParcelFileDescriptor mBackupData;
3966 private ParcelFileDescriptor mNewState;
3967 private PackageInfo mCurrentPackage;
3968
Christopher Tatedf01dea2009-06-09 20:45:02 -07003969
Christopher Tate5cbbf562009-06-22 16:44:51 -07003970 class RestoreRequest {
3971 public PackageInfo app;
3972 public int storedAppVersion;
3973
3974 RestoreRequest(PackageInfo _app, int _version) {
3975 app = _app;
3976 storedAppVersion = _version;
3977 }
3978 }
3979
Christopher Tate44a27902010-01-27 17:15:49 -08003980 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003981 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003982 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07003983 mCurrentState = RestoreState.INITIAL;
3984 mFinished = false;
3985 mPmAgent = null;
3986
Christopher Tatedf01dea2009-06-09 20:45:02 -07003987 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003988 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003989 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003990 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003991 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003992 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003993
Christopher Tate284f1bb2011-07-07 14:31:18 -07003994 if (filterSet != null) {
3995 mFilterSet = new HashSet<String>();
3996 for (String pkg : filterSet) {
3997 mFilterSet.add(pkg);
3998 }
3999 } else {
4000 mFilterSet = null;
4001 }
4002
Christopher Tate5cb400b2009-06-25 16:03:14 -07004003 try {
4004 mStateDir = new File(mBaseStateDir, transport.transportDirName());
4005 } catch (RemoteException e) {
4006 // can't happen; the transport is local
4007 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004008 }
4009
Christopher Tate2982d062011-09-06 20:35:24 -07004010 // Execute one tick of whatever state machine the task implements
4011 @Override
4012 public void execute() {
4013 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4014 switch (mCurrentState) {
4015 case INITIAL:
4016 beginRestore();
4017 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004018
Christopher Tate2982d062011-09-06 20:35:24 -07004019 case DOWNLOAD_DATA:
4020 downloadRestoreData();
4021 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004022
Christopher Tate2982d062011-09-06 20:35:24 -07004023 case PM_METADATA:
4024 restorePmMetadata();
4025 break;
4026
4027 case RUNNING_QUEUE:
4028 restoreNextAgent();
4029 break;
4030
4031 case FINAL:
4032 if (!mFinished) finalizeRestore();
4033 else {
4034 Slog.e(TAG, "Duplicate finish");
4035 }
4036 mFinished = true;
4037 break;
4038 }
4039 }
4040
4041 // Initialize and set up for the PM metadata restore, which comes first
4042 void beginRestore() {
4043 // Don't account time doing the restore as inactivity of the app
4044 // that has opened a restore session.
4045 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4046
4047 // Assume error until we successfully init everything
4048 mStatus = BackupConstants.TRANSPORT_ERROR;
4049
Christopher Tatedf01dea2009-06-09 20:45:02 -07004050 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004051 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004052 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004053
Dan Egnorefe52642009-06-24 00:16:33 -07004054 // Get the list of all packages which have backup enabled.
4055 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004056 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004057 PackageInfo omPackage = new PackageInfo();
4058 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004059 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004060
Christopher Tate2982d062011-09-06 20:35:24 -07004061 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004062 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004063 // if there's a filter set, strip out anything that isn't
4064 // present before proceeding
4065 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004066 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4067 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004068 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004069 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004070 }
4071 }
Christopher Tate2982d062011-09-06 20:35:24 -07004072 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004073 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004074 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004075 Slog.i(TAG, " " + p);
4076 }
4077 }
4078 }
Christopher Tate2982d062011-09-06 20:35:24 -07004079 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004080 } else {
4081 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004082 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004083 }
Dan Egnorefe52642009-06-24 00:16:33 -07004084
Christopher Tate7d562ec2009-06-25 18:03:43 -07004085 // let the observer know that we're running
4086 if (mObserver != null) {
4087 try {
4088 // !!! TODO: get an actual count from the transport after
4089 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004090 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004091 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004092 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004093 mObserver = null;
4094 }
4095 }
Christopher Tate2982d062011-09-06 20:35:24 -07004096 } catch (RemoteException e) {
4097 // Something has gone catastrophically wrong with the transport
4098 Slog.e(TAG, "Error communicating with transport for restore");
4099 executeNextState(RestoreState.FINAL);
4100 return;
4101 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004102
Christopher Tate2982d062011-09-06 20:35:24 -07004103 mStatus = BackupConstants.TRANSPORT_OK;
4104 executeNextState(RestoreState.DOWNLOAD_DATA);
4105 }
4106
4107 void downloadRestoreData() {
4108 // Note that the download phase can be very time consuming, but we're executing
4109 // it inline here on the looper. This is "okay" because it is not calling out to
4110 // third party code; the transport is "trusted," and so we assume it is being a
4111 // good citizen and timing out etc when appropriate.
4112 //
4113 // TODO: when appropriate, move the download off the looper and rearrange the
4114 // error handling around that.
4115 try {
4116 mStatus = mTransport.startRestore(mToken,
4117 mRestorePackages.toArray(new PackageInfo[0]));
4118 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004119 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004120 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004121 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004122 return;
4123 }
Christopher Tate2982d062011-09-06 20:35:24 -07004124 } catch (RemoteException e) {
4125 Slog.e(TAG, "Error communicating with transport for restore");
4126 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4127 mStatus = BackupConstants.TRANSPORT_ERROR;
4128 executeNextState(RestoreState.FINAL);
4129 return;
4130 }
Dan Egnorefe52642009-06-24 00:16:33 -07004131
Christopher Tate2982d062011-09-06 20:35:24 -07004132 // Successful download of the data to be parceled out to the apps, so off we go.
4133 executeNextState(RestoreState.PM_METADATA);
4134 }
4135
4136 void restorePmMetadata() {
4137 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004138 String packageName = mTransport.nextRestorePackage();
4139 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004140 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004141 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004142 mStatus = BackupConstants.TRANSPORT_ERROR;
4143 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004144 return;
4145 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004146 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004147 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004148 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004149 mStatus = BackupConstants.TRANSPORT_OK;
4150 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004151 return;
4152 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004153 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004154 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004155 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004156 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004157 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004158 return;
4159 }
4160
4161 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004162 PackageInfo omPackage = new PackageInfo();
4163 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4164 mPmAgent = new PackageManagerBackupAgent(
4165 mPackageManager, mAgentPackages);
4166 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004167 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004168 // The PM agent called operationComplete() already, because our invocation
4169 // of it is process-local and therefore synchronous. That means that a
4170 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4171 // proceed with running the queue do we remove that pending message and
4172 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004173
Christopher Tate8c032472009-07-02 14:28:47 -07004174 // Verify that the backup set includes metadata. If not, we can't do
4175 // signature/version verification etc, so we simply do not proceed with
4176 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004177 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004178 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004179 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004180 "Package manager restore metadata missing");
4181 mStatus = BackupConstants.TRANSPORT_ERROR;
4182 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4183 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004184 return;
4185 }
Christopher Tate2982d062011-09-06 20:35:24 -07004186 } catch (RemoteException e) {
4187 Slog.e(TAG, "Error communicating with transport for restore");
4188 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4189 mStatus = BackupConstants.TRANSPORT_ERROR;
4190 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4191 executeNextState(RestoreState.FINAL);
4192 return;
4193 }
Christopher Tate8c032472009-07-02 14:28:47 -07004194
Christopher Tate2982d062011-09-06 20:35:24 -07004195 // Metadata is intact, so we can now run the restore queue. If we get here,
4196 // we have already enqueued the necessary next-step message on the looper.
4197 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004198
Christopher Tate2982d062011-09-06 20:35:24 -07004199 void restoreNextAgent() {
4200 try {
4201 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004202
Christopher Tate2982d062011-09-06 20:35:24 -07004203 if (packageName == null) {
4204 Slog.e(TAG, "Error getting next restore package");
4205 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4206 executeNextState(RestoreState.FINAL);
4207 return;
4208 } else if (packageName.equals("")) {
4209 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4210 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4211 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4212 executeNextState(RestoreState.FINAL);
4213 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004214 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004215
4216 if (mObserver != null) {
4217 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004218 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004219 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004220 Slog.d(TAG, "Restore observer died in onUpdate");
4221 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004222 }
4223 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004224
Christopher Tate2982d062011-09-06 20:35:24 -07004225 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4226 if (metaInfo == null) {
4227 Slog.e(TAG, "Missing metadata for " + packageName);
4228 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4229 "Package metadata missing");
4230 executeNextState(RestoreState.RUNNING_QUEUE);
4231 return;
Christopher Tate84725812010-02-04 15:52:40 -08004232 }
4233
Christopher Tate2982d062011-09-06 20:35:24 -07004234 PackageInfo packageInfo;
4235 try {
4236 int flags = PackageManager.GET_SIGNATURES;
4237 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4238 } catch (NameNotFoundException e) {
4239 Slog.e(TAG, "Invalid package restoring data", e);
4240 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4241 "Package missing on device");
4242 executeNextState(RestoreState.RUNNING_QUEUE);
4243 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004244 }
4245
Christopher Tate2982d062011-09-06 20:35:24 -07004246 if (metaInfo.versionCode > packageInfo.versionCode) {
4247 // Data is from a "newer" version of the app than we have currently
4248 // installed. If the app has not declared that it is prepared to
4249 // handle this case, we do not attempt the restore.
4250 if ((packageInfo.applicationInfo.flags
4251 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4252 String message = "Version " + metaInfo.versionCode
4253 + " > installed version " + packageInfo.versionCode;
4254 Slog.w(TAG, "Package " + packageName + ": " + message);
4255 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4256 packageName, message);
4257 executeNextState(RestoreState.RUNNING_QUEUE);
4258 return;
4259 } else {
4260 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4261 + " > installed " + packageInfo.versionCode
4262 + " but restoreAnyVersion");
4263 }
4264 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004265
Christopher Tate2982d062011-09-06 20:35:24 -07004266 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4267 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4268 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4269 "Signature mismatch");
4270 executeNextState(RestoreState.RUNNING_QUEUE);
4271 return;
4272 }
4273
4274 if (DEBUG) Slog.v(TAG, "Package " + packageName
4275 + " restore version [" + metaInfo.versionCode
4276 + "] is compatible with installed version ["
4277 + packageInfo.versionCode + "]");
4278
4279 // Then set up and bind the agent
4280 IBackupAgent agent = bindToAgentSynchronous(
4281 packageInfo.applicationInfo,
4282 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4283 if (agent == null) {
4284 Slog.w(TAG, "Can't find backup agent for " + packageName);
4285 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4286 "Restore agent missing");
4287 executeNextState(RestoreState.RUNNING_QUEUE);
4288 return;
4289 }
4290
4291 // And then finally start the restore on this agent
4292 try {
4293 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4294 ++mCount;
4295 } catch (Exception e) {
4296 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4297 agentErrorCleanup();
4298 executeNextState(RestoreState.RUNNING_QUEUE);
4299 }
4300 } catch (RemoteException e) {
4301 Slog.e(TAG, "Unable to fetch restore data from transport");
4302 mStatus = BackupConstants.TRANSPORT_ERROR;
4303 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004304 }
4305 }
4306
Christopher Tate2982d062011-09-06 20:35:24 -07004307 void finalizeRestore() {
4308 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4309
4310 try {
4311 mTransport.finishRestore();
4312 } catch (RemoteException e) {
4313 Slog.e(TAG, "Error finishing restore", e);
4314 }
4315
4316 if (mObserver != null) {
4317 try {
4318 mObserver.restoreFinished(mStatus);
4319 } catch (RemoteException e) {
4320 Slog.d(TAG, "Restore observer died at restoreFinished");
4321 }
4322 }
4323
4324 // If this was a restoreAll operation, record that this was our
4325 // ancestral dataset, as well as the set of apps that are possibly
4326 // restoreable from the dataset
4327 if (mTargetPackage == null && mPmAgent != null) {
4328 mAncestralPackages = mPmAgent.getRestoredPackages();
4329 mAncestralToken = mToken;
4330 writeRestoreTokens();
4331 }
4332
4333 // We must under all circumstances tell the Package Manager to
4334 // proceed with install notifications if it's waiting for us.
4335 if (mPmToken > 0) {
4336 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4337 try {
4338 mPackageManagerBinder.finishPackageInstall(mPmToken);
4339 } catch (RemoteException e) { /* can't happen */ }
4340 }
4341
4342 // Furthermore we need to reset the session timeout clock
4343 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4344 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4345 TIMEOUT_RESTORE_INTERVAL);
4346
4347 // done; we can finally release the wakelock
4348 Slog.i(TAG, "Restore complete.");
4349 mWakelock.release();
4350 }
4351
4352 // Call asynchronously into the app, passing it the restore data. The next step
4353 // after this is always a callback, either operationComplete() or handleTimeout().
4354 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004355 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004356 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004357 final String packageName = app.packageName;
4358
Christopher Tate2982d062011-09-06 20:35:24 -07004359 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004360
Christopher Tatec7b31e32009-06-10 15:49:30 -07004361 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004362 mBackupDataName = new File(mDataDir, packageName + ".restore");
4363 mNewStateName = new File(mStateDir, packageName + ".new");
4364 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004365
Christopher Tate4a627c72011-04-01 14:43:32 -07004366 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004367 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004368 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004369 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004370 ParcelFileDescriptor.MODE_READ_WRITE |
4371 ParcelFileDescriptor.MODE_CREATE |
4372 ParcelFileDescriptor.MODE_TRUNCATE);
4373
Christopher Tate2982d062011-09-06 20:35:24 -07004374 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004375 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004376 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004377 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004378 }
4379
4380 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004381 mBackupData.close();
4382 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004383 ParcelFileDescriptor.MODE_READ_ONLY);
4384
Christopher Tate2982d062011-09-06 20:35:24 -07004385 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004386 ParcelFileDescriptor.MODE_READ_WRITE |
4387 ParcelFileDescriptor.MODE_CREATE |
4388 ParcelFileDescriptor.MODE_TRUNCATE);
4389
Christopher Tate44a27902010-01-27 17:15:49 -08004390 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004391 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4392 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004393 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004394 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004395 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004396 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004397
Christopher Tate2982d062011-09-06 20:35:24 -07004398 // After a restore failure we go back to running the queue. If there
4399 // are no more packages to be restored that will be handled by the
4400 // next step.
4401 executeNextState(RestoreState.RUNNING_QUEUE);
4402 }
4403 }
Chris Tate249345b2010-10-29 12:57:04 -07004404
Christopher Tate2982d062011-09-06 20:35:24 -07004405 void agentErrorCleanup() {
4406 // If the agent fails restore, it might have put the app's data
4407 // into an incoherent state. For consistency we wipe its data
4408 // again in this case before continuing with normal teardown
4409 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4410 agentCleanup();
4411 }
4412
4413 void agentCleanup() {
4414 mBackupDataName.delete();
4415 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4416 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4417 mBackupData = mNewState = null;
4418
4419 // if everything went okay, remember the recorded state now
4420 //
4421 // !!! TODO: the restored data should be migrated on the server
4422 // side into the current dataset. In that case the new state file
4423 // we just created would reflect the data already extant in the
4424 // backend, so there'd be nothing more to do. Until that happens,
4425 // however, we need to make sure that we record the data to the
4426 // current backend dataset. (Yes, this means shipping the data over
4427 // the wire in both directions. That's bad, but consistency comes
4428 // first, then efficiency.) Once we introduce server-side data
4429 // migration to the newly-restored device's dataset, we will change
4430 // the following from a discard of the newly-written state to the
4431 // "correct" operation of renaming into the canonical state blob.
4432 mNewStateName.delete(); // TODO: remove; see above comment
4433 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4434
4435 // If this wasn't the PM pseudopackage, tear down the agent side
4436 if (mCurrentPackage.applicationInfo != null) {
4437 // unbind and tidy up even on timeout or failure
4438 try {
4439 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4440
4441 // The agent was probably running with a stub Application object,
4442 // which isn't a valid run mode for the main app logic. Shut
4443 // down the app so that next time it's launched, it gets the
4444 // usual full initialization. Note that this is only done for
4445 // full-system restores: when a single app has requested a restore,
4446 // it is explicitly not killed following that operation.
4447 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4448 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4449 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4450 + mCurrentPackage.applicationInfo.processName);
4451 mActivityManager.killApplicationProcess(
4452 mCurrentPackage.applicationInfo.processName,
4453 mCurrentPackage.applicationInfo.uid);
4454 }
4455 } catch (RemoteException e) {
4456 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004457 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004458 }
Christopher Tate2982d062011-09-06 20:35:24 -07004459
4460 // The caller is responsible for reestablishing the state machine; our
4461 // responsibility here is to clear the decks for whatever comes next.
4462 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4463 synchronized (mCurrentOpLock) {
4464 mCurrentOperations.clear();
4465 }
4466 }
4467
4468 // A call to agent.doRestore() has been positively acknowledged as complete
4469 @Override
4470 public void operationComplete() {
4471 int size = (int) mBackupDataName.length();
4472 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4473 // Just go back to running the restore queue
4474 agentCleanup();
4475
4476 executeNextState(RestoreState.RUNNING_QUEUE);
4477 }
4478
4479 // A call to agent.doRestore() has timed out
4480 @Override
4481 public void handleTimeout() {
4482 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4483 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4484 mCurrentPackage.packageName, "restore timeout");
4485 // Handle like an agent that threw on invocation: wipe it and go on to the next
4486 agentErrorCleanup();
4487 executeNextState(RestoreState.RUNNING_QUEUE);
4488 }
4489
4490 void executeNextState(RestoreState nextState) {
4491 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4492 + this + " nextState=" + nextState);
4493 mCurrentState = nextState;
4494 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4495 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004496 }
4497 }
4498
Christopher Tate44a27902010-01-27 17:15:49 -08004499 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004500 IBackupTransport mTransport;
4501 PackageInfo mPackage;
4502
Christopher Tate44a27902010-01-27 17:15:49 -08004503 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004504 mTransport = transport;
4505 mPackage = packageInfo;
4506 }
4507
Christopher Tateee0e78a2009-07-02 11:17:03 -07004508 public void run() {
4509 try {
4510 // Clear the on-device backup state to ensure a full backup next time
4511 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4512 File stateFile = new File(stateDir, mPackage.packageName);
4513 stateFile.delete();
4514
4515 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004516 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004517 mTransport.clearBackupData(mPackage);
4518 } catch (RemoteException e) {
4519 // can't happen; the transport is local
4520 } finally {
4521 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004522 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004523 mTransport.finishBackup();
4524 } catch (RemoteException e) {
4525 // can't happen; the transport is local
4526 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004527
4528 // Last but not least, release the cpu
4529 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004530 }
4531 }
4532 }
4533
Christopher Tate44a27902010-01-27 17:15:49 -08004534 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004535 HashSet<String> mQueue;
4536
Christopher Tate44a27902010-01-27 17:15:49 -08004537 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004538 mQueue = transportNames;
4539 }
4540
Christopher Tate4cc86e12009-09-21 19:36:51 -07004541 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004542 try {
4543 for (String transportName : mQueue) {
4544 IBackupTransport transport = getTransport(transportName);
4545 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004546 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004547 continue;
4548 }
4549
Joe Onorato8a9b2202010-02-26 18:56:32 -08004550 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004551 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004552 long startRealtime = SystemClock.elapsedRealtime();
4553 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004554
Christopher Tate4cc86e12009-09-21 19:36:51 -07004555 if (status == BackupConstants.TRANSPORT_OK) {
4556 status = transport.finishBackup();
4557 }
4558
4559 // Okay, the wipe really happened. Clean up our local bookkeeping.
4560 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004561 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004562 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004563 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004564 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004565 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004566 synchronized (mQueueLock) {
4567 recordInitPendingLocked(false, transportName);
4568 }
Dan Egnor726247c2009-09-29 19:12:31 -07004569 } else {
4570 // If this didn't work, requeue this one and try again
4571 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004572 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004573 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004574 synchronized (mQueueLock) {
4575 recordInitPendingLocked(true, transportName);
4576 }
4577 // do this via another alarm to make sure of the wakelock states
4578 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004579 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004580 + transportName + " resched in " + delay);
4581 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4582 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004583 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004584 }
4585 } catch (RemoteException e) {
4586 // can't happen; the transports are local
4587 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004588 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004589 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004590 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004591 mWakelock.release();
4592 }
4593 }
4594 }
4595
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004596 private void dataChangedImpl(String packageName) {
4597 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4598 dataChangedImpl(packageName, targets);
4599 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004600
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004601 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004602 // Record that we need a backup pass for the caller. Since multiple callers
4603 // may share a uid, we need to note all candidates within that uid and schedule
4604 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004605 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004606
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004607 if (targets == null) {
4608 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4609 + " uid=" + Binder.getCallingUid());
4610 return;
4611 }
4612
4613 synchronized (mQueueLock) {
4614 // Note that this client has made data changes that need to be backed up
4615 for (ApplicationInfo app : targets) {
4616 // validate the caller-supplied package name against the known set of
4617 // packages associated with this uid
4618 if (app.packageName.equals(packageName)) {
4619 // Add the caller to the set of pending backups. If there is
4620 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004621 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004622 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004623 // Journal this request in case of crash. The put()
4624 // operation returned null when this package was not already
4625 // in the set; we want to avoid touching the disk redundantly.
4626 writeToJournalLocked(packageName);
4627
Christopher Tatec58efa62011-08-01 19:20:14 -07004628 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004629 int numKeys = mPendingBackups.size();
4630 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4631 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004632 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004633 }
4634 }
4635 }
4636 }
4637 }
4638 }
4639 }
4640
4641 // Note: packageName is currently unused, but may be in the future
4642 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004643 // If the caller does not hold the BACKUP permission, it can only request a
4644 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004645 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004646 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004647 synchronized (mBackupParticipants) {
4648 return mBackupParticipants.get(Binder.getCallingUid());
4649 }
4650 }
4651
4652 // a caller with full permission can ask to back up any participating app
4653 // !!! TODO: allow backup of ANY app?
4654 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4655 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004656 int N = mBackupParticipants.size();
4657 for (int i = 0; i < N; i++) {
4658 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4659 if (s != null) {
4660 targets.addAll(s);
4661 }
4662 }
4663 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004664 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004665 }
Christopher Tate46758122009-05-06 11:22:00 -07004666
Christopher Tatecde87f42009-06-12 12:55:53 -07004667 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004668 RandomAccessFile out = null;
4669 try {
4670 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4671 out = new RandomAccessFile(mJournal, "rws");
4672 out.seek(out.length());
4673 out.writeUTF(str);
4674 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004675 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004676 mJournal = null;
4677 } finally {
4678 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004679 }
4680 }
4681
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004682 // ----- IBackupManager binder interface -----
4683
4684 public void dataChanged(final String packageName) {
4685 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4686 if (targets == null) {
4687 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4688 + " uid=" + Binder.getCallingUid());
4689 return;
4690 }
4691
4692 mBackupHandler.post(new Runnable() {
4693 public void run() {
4694 dataChangedImpl(packageName, targets);
4695 }
4696 });
4697 }
4698
Christopher Tateee0e78a2009-07-02 11:17:03 -07004699 // Clear the given package's backup data from the current transport
4700 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004701 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004702 PackageInfo info;
4703 try {
4704 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4705 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004706 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004707 return;
4708 }
4709
4710 // If the caller does not hold the BACKUP permission, it can only request a
4711 // wipe of its own backed-up data.
4712 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004713 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004714 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4715 apps = mBackupParticipants.get(Binder.getCallingUid());
4716 } else {
4717 // a caller with full permission can ask to back up any participating app
4718 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004719 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004720 apps = new HashSet<ApplicationInfo>();
4721 int N = mBackupParticipants.size();
4722 for (int i = 0; i < N; i++) {
4723 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4724 if (s != null) {
4725 apps.addAll(s);
4726 }
4727 }
4728 }
4729
4730 // now find the given package in the set of candidate apps
4731 for (ApplicationInfo app : apps) {
4732 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004733 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004734 // found it; fire off the clear request
4735 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004736 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004737 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004738 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4739 new ClearParams(getTransport(mCurrentTransport), info));
4740 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004741 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004742 }
4743 break;
4744 }
4745 }
4746 }
4747
Christopher Tateace7f092009-06-15 18:07:25 -07004748 // Run a backup pass immediately for any applications that have declared
4749 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004750 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004751 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004752
Joe Onorato8a9b2202010-02-26 18:56:32 -08004753 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004754 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004755 // Because the alarms we are using can jitter, and we want an *immediate*
4756 // backup pass to happen, we restart the timer beginning with "next time,"
4757 // then manually fire the backup trigger intent ourselves.
4758 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004759 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004760 mRunBackupIntent.send();
4761 } catch (PendingIntent.CanceledException e) {
4762 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004763 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004764 }
Christopher Tate46758122009-05-06 11:22:00 -07004765 }
4766 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004767
Christopher Tate4a627c72011-04-01 14:43:32 -07004768 // Run a *full* backup pass for the given package, writing the resulting data stream
4769 // to the supplied file descriptor. This method is synchronous and does not return
4770 // to the caller until the backup has been completed.
4771 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4772 boolean doAllApps, String[] pkgList) {
4773 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4774
4775 // Validate
4776 if (!doAllApps) {
4777 if (!includeShared) {
4778 // If we're backing up shared data (sdcard or equivalent), then we can run
4779 // without any supplied app names. Otherwise, we'd be doing no work, so
4780 // report the error.
4781 if (pkgList == null || pkgList.length == 0) {
4782 throw new IllegalArgumentException(
4783 "Backup requested but neither shared nor any apps named");
4784 }
4785 }
4786 }
4787
4788 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4789 + " shared=" + includeShared + " all=" + doAllApps
4790 + " pkgs=" + pkgList);
4791
4792 long oldId = Binder.clearCallingIdentity();
4793 try {
4794 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4795 doAllApps, pkgList);
4796 final int token = generateToken();
4797 synchronized (mFullConfirmations) {
4798 mFullConfirmations.put(token, params);
4799 }
4800
Christopher Tate75a99702011-05-18 16:28:19 -07004801 // start up the confirmation UI
4802 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4803 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4804 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004805 mFullConfirmations.delete(token);
4806 return;
4807 }
Christopher Tate75a99702011-05-18 16:28:19 -07004808
4809 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004810 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4811
4812 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004813 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004814
4815 // wait for the backup to be performed
4816 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4817 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004818 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004819 try {
4820 fd.close();
4821 } catch (IOException e) {
4822 // just eat it
4823 }
Christopher Tate75a99702011-05-18 16:28:19 -07004824 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07004825 }
Christopher Tatec58efa62011-08-01 19:20:14 -07004826 if (MORE_DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
Christopher Tate75a99702011-05-18 16:28:19 -07004827 }
4828
4829 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004830 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004831 Slog.i(TAG, "Beginning full restore...");
4832
4833 long oldId = Binder.clearCallingIdentity();
4834
4835 try {
4836 FullRestoreParams params = new FullRestoreParams(fd);
4837 final int token = generateToken();
4838 synchronized (mFullConfirmations) {
4839 mFullConfirmations.put(token, params);
4840 }
4841
4842 // start up the confirmation UI
4843 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4844 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4845 Slog.e(TAG, "Unable to launch full restore confirmation");
4846 mFullConfirmations.delete(token);
4847 return;
4848 }
4849
4850 // make sure the screen is lit for the user interaction
4851 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4852
4853 // start the confirmation countdown
4854 startConfirmationTimeout(token, params);
4855
4856 // wait for the restore to be performed
4857 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4858 waitForCompletion(params);
4859 } finally {
4860 try {
4861 fd.close();
4862 } catch (IOException e) {
4863 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4864 }
4865 Binder.restoreCallingIdentity(oldId);
4866 Slog.i(TAG, "Full restore completed");
4867 }
4868 }
4869
4870 boolean startConfirmationUi(int token, String action) {
4871 try {
4872 Intent confIntent = new Intent(action);
4873 confIntent.setClassName("com.android.backupconfirm",
4874 "com.android.backupconfirm.BackupRestoreConfirmation");
4875 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4876 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4877 mContext.startActivity(confIntent);
4878 } catch (ActivityNotFoundException e) {
4879 return false;
4880 }
4881 return true;
4882 }
4883
4884 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004885 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004886 + TIMEOUT_FULL_CONFIRMATION + " millis");
4887 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4888 token, 0, params);
4889 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004890 }
4891
4892 void waitForCompletion(FullParams params) {
4893 synchronized (params.latch) {
4894 while (params.latch.get() == false) {
4895 try {
4896 params.latch.wait();
4897 } catch (InterruptedException e) { /* never interrupted */ }
4898 }
4899 }
4900 }
4901
4902 void signalFullBackupRestoreCompletion(FullParams params) {
4903 synchronized (params.latch) {
4904 params.latch.set(true);
4905 params.latch.notifyAll();
4906 }
4907 }
4908
4909 // Confirm that the previously-requested full backup/restore operation can proceed. This
4910 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004911 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004912 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004913 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004914 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4915 + " allow=" + allow);
4916
4917 // TODO: possibly require not just this signature-only permission, but even
4918 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004919 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004920
4921 long oldId = Binder.clearCallingIdentity();
4922 try {
4923
4924 FullParams params;
4925 synchronized (mFullConfirmations) {
4926 params = mFullConfirmations.get(token);
4927 if (params != null) {
4928 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4929 mFullConfirmations.delete(token);
4930
4931 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004932 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004933 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004934 : MSG_RUN_FULL_RESTORE;
4935
Christopher Tate728a1c42011-07-28 18:03:03 -07004936 params.observer = observer;
4937 params.curPassword = curPassword;
4938 params.encryptPassword = encPpassword;
4939
Christopher Tate75a99702011-05-18 16:28:19 -07004940 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004941 mWakelock.acquire();
4942 Message msg = mBackupHandler.obtainMessage(verb, params);
4943 mBackupHandler.sendMessage(msg);
4944 } else {
4945 Slog.w(TAG, "User rejected full backup/restore operation");
4946 // indicate completion without having actually transferred any data
4947 signalFullBackupRestoreCompletion(params);
4948 }
4949 } else {
4950 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4951 }
4952 }
4953 } finally {
4954 Binder.restoreCallingIdentity(oldId);
4955 }
4956 }
4957
Christopher Tate8031a3d2009-07-06 16:36:05 -07004958 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004959 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004960 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004961 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004962
Joe Onorato8a9b2202010-02-26 18:56:32 -08004963 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004964
Christopher Tate6ef58a12009-06-29 14:56:28 -07004965 boolean wasEnabled = mEnabled;
4966 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004967 Settings.Secure.putInt(mContext.getContentResolver(),
4968 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004969 mEnabled = enable;
4970 }
4971
Christopher Tate49401dd2009-07-01 12:34:29 -07004972 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004973 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004974 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004975 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004976 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004977 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004978 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004979
Christopher Tateb6787f22009-07-02 17:40:45 -07004980 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004981
4982 // This also constitutes an opt-out, so we wipe any data for
4983 // this device from the backend. We start that process with
4984 // an alarm in order to guarantee wakelock states.
4985 if (wasEnabled && mProvisioned) {
4986 // NOTE: we currently flush every registered transport, not just
4987 // the currently-active one.
4988 HashSet<String> allTransports;
4989 synchronized (mTransports) {
4990 allTransports = new HashSet<String>(mTransports.keySet());
4991 }
4992 // build the set of transports for which we are posting an init
4993 for (String transport : allTransports) {
4994 recordInitPendingLocked(true, transport);
4995 }
4996 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4997 mRunInitIntent);
4998 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004999 }
5000 }
Christopher Tate49401dd2009-07-01 12:34:29 -07005001 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07005002
Christopher Tatecce9da52010-02-03 15:11:15 -08005003 // Enable/disable automatic restore of app data at install time
5004 public void setAutoRestore(boolean doAutoRestore) {
5005 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005006 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08005007
Joe Onorato8a9b2202010-02-26 18:56:32 -08005008 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005009
5010 synchronized (this) {
5011 Settings.Secure.putInt(mContext.getContentResolver(),
5012 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5013 mAutoRestore = doAutoRestore;
5014 }
5015 }
5016
Christopher Tate8031a3d2009-07-06 16:36:05 -07005017 // Mark the backup service as having been provisioned
5018 public void setBackupProvisioned(boolean available) {
5019 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5020 "setBackupProvisioned");
5021
5022 boolean wasProvisioned = mProvisioned;
5023 synchronized (this) {
5024 Settings.Secure.putInt(mContext.getContentResolver(),
5025 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
5026 mProvisioned = available;
5027 }
5028
5029 synchronized (mQueueLock) {
5030 if (available && !wasProvisioned && mEnabled) {
5031 // we're now good to go, so start the backup alarms
5032 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
5033 } else if (!available) {
5034 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005035 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07005036 mAlarmManager.cancel(mRunBackupIntent);
5037 }
5038 }
5039 }
5040
5041 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005042 // We used to use setInexactRepeating(), but that may be linked to
5043 // backups running at :00 more often than not, creating load spikes.
5044 // Schedule at an exact time for now, and also add a bit of "fuzz".
5045
5046 Random random = new Random();
5047 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5048 random.nextInt(FUZZ_MILLIS);
5049 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5050 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005051 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005052 }
5053
Christopher Tate6ef58a12009-06-29 14:56:28 -07005054 // Report whether the backup mechanism is currently enabled
5055 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005056 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005057 return mEnabled; // no need to synchronize just to read it
5058 }
5059
Christopher Tate91717492009-06-26 21:07:13 -07005060 // Report the name of the currently active transport
5061 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005062 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005063 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005064 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005065 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005066 }
5067
Christopher Tate91717492009-06-26 21:07:13 -07005068 // Report all known, available backup transports
5069 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005070 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005071
Christopher Tate91717492009-06-26 21:07:13 -07005072 String[] list = null;
5073 ArrayList<String> known = new ArrayList<String>();
5074 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5075 if (entry.getValue() != null) {
5076 known.add(entry.getKey());
5077 }
5078 }
5079
5080 if (known.size() > 0) {
5081 list = new String[known.size()];
5082 known.toArray(list);
5083 }
5084 return list;
5085 }
5086
5087 // Select which transport to use for the next backup operation. If the given
5088 // name is not one of the available transports, no action is taken and the method
5089 // returns null.
5090 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005091 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005092
5093 synchronized (mTransports) {
5094 String prevTransport = null;
5095 if (mTransports.get(transport) != null) {
5096 prevTransport = mCurrentTransport;
5097 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005098 Settings.Secure.putString(mContext.getContentResolver(),
5099 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005100 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005101 + " returning " + prevTransport);
5102 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005103 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005104 }
5105 return prevTransport;
5106 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005107 }
5108
Christopher Tatef5e1c292010-12-08 18:40:26 -08005109 // Supply the configuration Intent for the given transport. If the name is not one
5110 // of the available transports, or if the transport does not supply any configuration
5111 // UI, the method returns null.
5112 public Intent getConfigurationIntent(String transportName) {
5113 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5114 "getConfigurationIntent");
5115
5116 synchronized (mTransports) {
5117 final IBackupTransport transport = mTransports.get(transportName);
5118 if (transport != null) {
5119 try {
5120 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005121 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005122 + intent);
5123 return intent;
5124 } catch (RemoteException e) {
5125 /* fall through to return null */
5126 }
5127 }
5128 }
5129
5130 return null;
5131 }
5132
5133 // Supply the configuration summary string for the given transport. If the name is
5134 // not one of the available transports, or if the transport does not supply any
5135 // summary / destination string, the method can return null.
5136 //
5137 // This string is used VERBATIM as the summary text of the relevant Settings item!
5138 public String getDestinationString(String transportName) {
5139 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005140 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005141
5142 synchronized (mTransports) {
5143 final IBackupTransport transport = mTransports.get(transportName);
5144 if (transport != null) {
5145 try {
5146 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005147 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005148 return text;
5149 } catch (RemoteException e) {
5150 /* fall through to return null */
5151 }
5152 }
5153 }
5154
5155 return null;
5156 }
5157
Christopher Tate043dadc2009-06-02 16:11:00 -07005158 // Callback: a requested backup agent has been instantiated. This should only
5159 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005160 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005161 synchronized(mAgentConnectLock) {
5162 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005163 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005164 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5165 mConnectedAgent = agent;
5166 mConnecting = false;
5167 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005168 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005169 + " claiming agent connected");
5170 }
5171 mAgentConnectLock.notifyAll();
5172 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005173 }
5174
5175 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5176 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005177 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005178 public void agentDisconnected(String packageName) {
5179 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005180 synchronized(mAgentConnectLock) {
5181 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5182 mConnectedAgent = null;
5183 mConnecting = false;
5184 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005185 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005186 + " claiming agent disconnected");
5187 }
5188 mAgentConnectLock.notifyAll();
5189 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005190 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005191
Christopher Tate1bb69062010-02-19 17:02:12 -08005192 // An application being installed will need a restore pass, then the Package Manager
5193 // will need to be told when the restore is finished.
5194 public void restoreAtInstall(String packageName, int token) {
5195 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005196 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005197 + " attemping install-time restore");
5198 return;
5199 }
5200
5201 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005202 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005203 + " token=" + Integer.toHexString(token));
5204
Christopher Tatef0872722010-02-25 15:22:48 -08005205 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005206 // okay, we're going to attempt a restore of this package from this restore set.
5207 // The eventual message back into the Package Manager to run the post-install
5208 // steps for 'token' will be issued from the restore handling code.
5209
5210 // We can use a synthetic PackageInfo here because:
5211 // 1. We know it's valid, since the Package Manager supplied the name
5212 // 2. Only the packageName field will be used by the restore code
5213 PackageInfo pkg = new PackageInfo();
5214 pkg.packageName = packageName;
5215
5216 mWakelock.acquire();
5217 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5218 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005219 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005220 mBackupHandler.sendMessage(msg);
5221 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005222 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5223 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005224 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005225 try {
5226 mPackageManagerBinder.finishPackageInstall(token);
5227 } catch (RemoteException e) { /* can't happen */ }
5228 }
5229 }
5230
Christopher Tate8c850b72009-06-07 19:33:20 -07005231 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005232 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5233 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5234 + " transport=" + transport);
5235
5236 boolean needPermission = true;
5237 if (transport == null) {
5238 transport = mCurrentTransport;
5239
5240 if (packageName != null) {
5241 PackageInfo app = null;
5242 try {
5243 app = mPackageManager.getPackageInfo(packageName, 0);
5244 } catch (NameNotFoundException nnf) {
5245 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5246 throw new IllegalArgumentException("Package " + packageName + " not found");
5247 }
5248
5249 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5250 // So: using the current active transport, and the caller has asked
5251 // that its own package will be restored. In this narrow use case
5252 // we do not require the caller to hold the permission.
5253 needPermission = false;
5254 }
5255 }
5256 }
5257
5258 if (needPermission) {
5259 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5260 "beginRestoreSession");
5261 } else {
5262 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5263 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005264
5265 synchronized(this) {
5266 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005267 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005268 return null;
5269 }
Chris Tate44ab8452010-11-16 15:10:49 -08005270 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005271 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005272 }
5273 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005274 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005275
Christopher Tate73a3cb32010-12-13 18:27:26 -08005276 void clearRestoreSession(ActiveRestoreSession currentSession) {
5277 synchronized(this) {
5278 if (currentSession != mActiveRestoreSession) {
5279 Slog.e(TAG, "ending non-current restore session");
5280 } else {
5281 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5282 mActiveRestoreSession = null;
5283 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5284 }
5285 }
5286 }
5287
Christopher Tate44a27902010-01-27 17:15:49 -08005288 // Note that a currently-active backup agent has notified us that it has
5289 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005290 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005291 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005292 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5293 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005294 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005295 op = mCurrentOperations.get(token);
5296 if (op != null) {
5297 op.state = OP_ACKNOWLEDGED;
5298 }
Christopher Tate44a27902010-01-27 17:15:49 -08005299 mCurrentOpLock.notifyAll();
5300 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005301
5302 // The completion callback, if any, is invoked on the handler
5303 if (op != null && op.callback != null) {
5304 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5305 mBackupHandler.sendMessage(msg);
5306 }
Christopher Tate44a27902010-01-27 17:15:49 -08005307 }
5308
Christopher Tate9b3905c2009-06-08 15:24:01 -07005309 // ----- Restore session -----
5310
Christopher Tate80202c82010-01-25 19:37:47 -08005311 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005312 private static final String TAG = "RestoreSession";
5313
Chris Tate44ab8452010-11-16 15:10:49 -08005314 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005315 private IBackupTransport mRestoreTransport = null;
5316 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005317 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005318
Chris Tate44ab8452010-11-16 15:10:49 -08005319 ActiveRestoreSession(String packageName, String transport) {
5320 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005321 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005322 }
5323
5324 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005325 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005326 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005327 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005328 if (observer == null) {
5329 throw new IllegalArgumentException("Observer must not be null");
5330 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005331
Christopher Tate73a3cb32010-12-13 18:27:26 -08005332 if (mEnded) {
5333 throw new IllegalStateException("Restore session already ended");
5334 }
5335
Christopher Tate1bb69062010-02-19 17:02:12 -08005336 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005337 try {
Christopher Tate43383042009-07-13 15:17:13 -07005338 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005339 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005340 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005341 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005342 // spin off the transport request to our service thread
5343 mWakelock.acquire();
5344 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5345 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5346 mBackupHandler.sendMessage(msg);
5347 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005348 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005349 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005350 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005351 } finally {
5352 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005353 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005354 }
5355
Christopher Tate84725812010-02-04 15:52:40 -08005356 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005357 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5358 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005359
Chris Tate44ab8452010-11-16 15:10:49 -08005360 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005361 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005362
Christopher Tate73a3cb32010-12-13 18:27:26 -08005363 if (mEnded) {
5364 throw new IllegalStateException("Restore session already ended");
5365 }
5366
Dan Egnor0084da52009-07-29 12:57:16 -07005367 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005368 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5369 return -1;
5370 }
5371
5372 if (mPackageName != null) {
5373 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005374 return -1;
5375 }
5376
Christopher Tate21ab6a52009-09-24 18:01:46 -07005377 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005378 for (int i = 0; i < mRestoreSets.length; i++) {
5379 if (token == mRestoreSets[i].token) {
5380 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005381 mWakelock.acquire();
5382 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005383 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005384 mBackupHandler.sendMessage(msg);
5385 Binder.restoreCallingIdentity(oldId);
5386 return 0;
5387 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005388 }
5389 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005390
Joe Onorato8a9b2202010-02-26 18:56:32 -08005391 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005392 return -1;
5393 }
5394
Christopher Tate284f1bb2011-07-07 14:31:18 -07005395 public synchronized int restoreSome(long token, IRestoreObserver observer,
5396 String[] packages) {
5397 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5398 "performRestore");
5399
5400 if (DEBUG) {
5401 StringBuilder b = new StringBuilder(128);
5402 b.append("restoreSome token=");
5403 b.append(Long.toHexString(token));
5404 b.append(" observer=");
5405 b.append(observer.toString());
5406 b.append(" packages=");
5407 if (packages == null) {
5408 b.append("null");
5409 } else {
5410 b.append('{');
5411 boolean first = true;
5412 for (String s : packages) {
5413 if (!first) {
5414 b.append(", ");
5415 } else first = false;
5416 b.append(s);
5417 }
5418 b.append('}');
5419 }
5420 Slog.d(TAG, b.toString());
5421 }
5422
5423 if (mEnded) {
5424 throw new IllegalStateException("Restore session already ended");
5425 }
5426
5427 if (mRestoreTransport == null || mRestoreSets == null) {
5428 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5429 return -1;
5430 }
5431
5432 if (mPackageName != null) {
5433 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5434 return -1;
5435 }
5436
5437 synchronized (mQueueLock) {
5438 for (int i = 0; i < mRestoreSets.length; i++) {
5439 if (token == mRestoreSets[i].token) {
5440 long oldId = Binder.clearCallingIdentity();
5441 mWakelock.acquire();
5442 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5443 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5444 packages, true);
5445 mBackupHandler.sendMessage(msg);
5446 Binder.restoreCallingIdentity(oldId);
5447 return 0;
5448 }
5449 }
5450 }
5451
5452 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5453 return -1;
5454 }
5455
Christopher Tate84725812010-02-04 15:52:40 -08005456 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005457 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005458
Christopher Tate73a3cb32010-12-13 18:27:26 -08005459 if (mEnded) {
5460 throw new IllegalStateException("Restore session already ended");
5461 }
5462
Chris Tate44ab8452010-11-16 15:10:49 -08005463 if (mPackageName != null) {
5464 if (! mPackageName.equals(packageName)) {
5465 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5466 + " on session for package " + mPackageName);
5467 return -1;
5468 }
5469 }
5470
Christopher Tate84725812010-02-04 15:52:40 -08005471 PackageInfo app = null;
5472 try {
5473 app = mPackageManager.getPackageInfo(packageName, 0);
5474 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005475 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005476 return -1;
5477 }
5478
5479 // If the caller is not privileged and is not coming from the target
5480 // app's uid, throw a permission exception back to the caller.
5481 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5482 Binder.getCallingPid(), Binder.getCallingUid());
5483 if ((perm == PackageManager.PERMISSION_DENIED) &&
5484 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005485 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005486 + " or calling uid=" + Binder.getCallingUid());
5487 throw new SecurityException("No permission to restore other packages");
5488 }
5489
Christopher Tate7d411a32010-02-26 11:27:08 -08005490 // If the package has no backup agent, we obviously cannot proceed
5491 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005492 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005493 return -1;
5494 }
5495
Christopher Tate84725812010-02-04 15:52:40 -08005496 // So far so good; we're allowed to try to restore this package. Now
5497 // check whether there is data for it in the current dataset, falling back
5498 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005499 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005500
5501 // If we didn't come up with a place to look -- no ancestral dataset and
5502 // the app has never been backed up from this device -- there's nothing
5503 // to do but return failure.
5504 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005505 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005506 return -1;
5507 }
5508
5509 // Ready to go: enqueue the restore request and claim success
5510 long oldId = Binder.clearCallingIdentity();
5511 mWakelock.acquire();
5512 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005513 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005514 mBackupHandler.sendMessage(msg);
5515 Binder.restoreCallingIdentity(oldId);
5516 return 0;
5517 }
5518
Christopher Tate73a3cb32010-12-13 18:27:26 -08005519 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5520 class EndRestoreRunnable implements Runnable {
5521 BackupManagerService mBackupManager;
5522 ActiveRestoreSession mSession;
5523
5524 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5525 mBackupManager = manager;
5526 mSession = session;
5527 }
5528
5529 public void run() {
5530 // clean up the session's bookkeeping
5531 synchronized (mSession) {
5532 try {
5533 if (mSession.mRestoreTransport != null) {
5534 mSession.mRestoreTransport.finishRestore();
5535 }
5536 } catch (Exception e) {
5537 Slog.e(TAG, "Error in finishRestore", e);
5538 } finally {
5539 mSession.mRestoreTransport = null;
5540 mSession.mEnded = true;
5541 }
5542 }
5543
5544 // clean up the BackupManagerService side of the bookkeeping
5545 // and cancel any pending timeout message
5546 mBackupManager.clearRestoreSession(mSession);
5547 }
5548 }
5549
Dan Egnor0084da52009-07-29 12:57:16 -07005550 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005551 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005552
Christopher Tate73a3cb32010-12-13 18:27:26 -08005553 if (mEnded) {
5554 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005555 }
5556
Christopher Tate73a3cb32010-12-13 18:27:26 -08005557 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005558 }
5559 }
5560
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005561 @Override
5562 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005563 long identityToken = Binder.clearCallingIdentity();
5564 try {
5565 dumpInternal(pw);
5566 } finally {
5567 Binder.restoreCallingIdentity(identityToken);
5568 }
5569 }
5570
5571 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005572 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005573 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005574 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005575 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005576 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005577 pw.println("Last backup pass: " + mLastBackupPass
5578 + " (now = " + System.currentTimeMillis() + ')');
5579 pw.println(" next scheduled: " + mNextBackupPass);
5580
Christopher Tate91717492009-06-26 21:07:13 -07005581 pw.println("Available transports:");
5582 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005583 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5584 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005585 IBackupTransport transport = getTransport(t);
5586 File dir = new File(mBaseStateDir, transport.transportDirName());
5587 pw.println(" destination: " + transport.currentDestinationString());
5588 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005589 for (File f : dir.listFiles()) {
5590 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5591 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005592 } catch (Exception e) {
5593 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005594 pw.println(" Error: " + e);
5595 }
Christopher Tate91717492009-06-26 21:07:13 -07005596 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005597
5598 pw.println("Pending init: " + mPendingInits.size());
5599 for (String s : mPendingInits) {
5600 pw.println(" " + s);
5601 }
5602
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005603 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005604 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005605 for (int i=0; i<N; i++) {
5606 int uid = mBackupParticipants.keyAt(i);
5607 pw.print(" uid: ");
5608 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005609 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5610 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005611 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005612 }
5613 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005614
Christopher Tateb49ceb32010-02-08 16:22:24 -08005615 pw.println("Ancestral packages: "
5616 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005617 if (mAncestralPackages != null) {
5618 for (String pkg : mAncestralPackages) {
5619 pw.println(" " + pkg);
5620 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005621 }
5622
Christopher Tate73e02522009-07-15 14:18:26 -07005623 pw.println("Ever backed up: " + mEverStoredApps.size());
5624 for (String pkg : mEverStoredApps) {
5625 pw.println(" " + pkg);
5626 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005627
5628 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005629 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005630 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005631 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005632 }
5633 }
Christopher Tate487529a2009-04-29 14:03:25 -07005634}