blob: be2ef822fc6176d19066b2755007009221370b2f [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 {
500 FullBackupParams params = (FullBackupParams)msg.obj;
501 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700502 params.includeShared, params.curPassword, params.encryptPassword,
503 params.allApps, params.packages, params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800504 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700505 }
Christopher Tate44a27902010-01-27 17:15:49 -0800506
507 case MSG_RUN_RESTORE:
508 {
509 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800510 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate2982d062011-09-06 20:35:24 -0700511 PerformRestoreTask task = new PerformRestoreTask(
512 params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700513 params.token, params.pkgInfo, params.pmToken,
Christopher Tate2982d062011-09-06 20:35:24 -0700514 params.needFullBackup, params.filterSet);
515 Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
516 sendMessage(restoreMsg);
Christopher Tate44a27902010-01-27 17:15:49 -0800517 break;
518 }
519
Christopher Tate75a99702011-05-18 16:28:19 -0700520 case MSG_RUN_FULL_RESTORE:
521 {
522 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tate728a1c42011-07-28 18:03:03 -0700523 (new PerformFullRestoreTask(params.fd, params.curPassword, params.encryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -0700524 params.observer, params.latch)).run();
Christopher Tate75a99702011-05-18 16:28:19 -0700525 break;
526 }
527
Christopher Tate44a27902010-01-27 17:15:49 -0800528 case MSG_RUN_CLEAR:
529 {
530 ClearParams params = (ClearParams)msg.obj;
531 (new PerformClearTask(params.transport, params.packageInfo)).run();
532 break;
533 }
534
535 case MSG_RUN_INITIALIZE:
536 {
537 HashSet<String> queue;
538
539 // Snapshot the pending-init queue and work on that
540 synchronized (mQueueLock) {
541 queue = new HashSet<String>(mPendingInits);
542 mPendingInits.clear();
543 }
544
545 (new PerformInitializeTask(queue)).run();
546 break;
547 }
548
Christopher Tate2d449afe2010-03-29 19:14:24 -0700549 case MSG_RUN_GET_RESTORE_SETS:
550 {
551 // Like other async operations, this is entered with the wakelock held
552 RestoreSet[] sets = null;
553 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
554 try {
555 sets = params.transport.getAvailableRestoreSets();
556 // cache the result in the active session
557 synchronized (params.session) {
558 params.session.mRestoreSets = sets;
559 }
560 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
561 } catch (Exception e) {
562 Slog.e(TAG, "Error from transport getting set list");
563 } finally {
564 if (params.observer != null) {
565 try {
566 params.observer.restoreSetsAvailable(sets);
567 } catch (RemoteException re) {
568 Slog.e(TAG, "Unable to report listing to observer");
569 } catch (Exception e) {
570 Slog.e(TAG, "Restore observer threw", e);
571 }
572 }
573
Christopher Tate2a935092011-03-03 17:30:32 -0800574 // Done: reset the session timeout clock
575 removeMessages(MSG_RESTORE_TIMEOUT);
576 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
577
Christopher Tate2d449afe2010-03-29 19:14:24 -0700578 mWakelock.release();
579 }
580 break;
581 }
582
Christopher Tate44a27902010-01-27 17:15:49 -0800583 case MSG_TIMEOUT:
584 {
Christopher Tate8e294d42011-08-31 20:37:12 -0700585 handleTimeout(msg.arg1, msg.obj);
Christopher Tate44a27902010-01-27 17:15:49 -0800586 break;
587 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800588
589 case MSG_RESTORE_TIMEOUT:
590 {
591 synchronized (BackupManagerService.this) {
592 if (mActiveRestoreSession != null) {
593 // Client app left the restore session dangling. We know that it
594 // can't be in the middle of an actual restore operation because
Christopher Tate2982d062011-09-06 20:35:24 -0700595 // the timeout is suspended while a restore is in progress. Clean
Christopher Tate73a3cb32010-12-13 18:27:26 -0800596 // up now.
597 Slog.w(TAG, "Restore session timed out; aborting");
598 post(mActiveRestoreSession.new EndRestoreRunnable(
599 BackupManagerService.this, mActiveRestoreSession));
600 }
601 }
602 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700603
604 case MSG_FULL_CONFIRMATION_TIMEOUT:
605 {
606 synchronized (mFullConfirmations) {
607 FullParams params = mFullConfirmations.get(msg.arg1);
608 if (params != null) {
609 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
610
611 // Release the waiter; timeout == completion
612 signalFullBackupRestoreCompletion(params);
613
614 // Remove the token from the set
615 mFullConfirmations.delete(msg.arg1);
616
617 // Report a timeout to the observer, if any
618 if (params.observer != null) {
619 try {
620 params.observer.onTimeout();
621 } catch (RemoteException e) {
622 /* don't care if the app has gone away */
623 }
624 }
625 } else {
626 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
627 }
628 }
629 break;
630 }
Christopher Tate44a27902010-01-27 17:15:49 -0800631 }
632 }
633 }
634
635 // ----- Main service implementation -----
636
Christopher Tate487529a2009-04-29 14:03:25 -0700637 public BackupManagerService(Context context) {
638 mContext = context;
639 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700640 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700641 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700642
Christopher Tateb6787f22009-07-02 17:40:45 -0700643 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
644 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
645
Christopher Tate44a27902010-01-27 17:15:49 -0800646 mBackupManagerBinder = asInterface(asBinder());
647
648 // spin up the backup/restore handler thread
649 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
650 mHandlerThread.start();
651 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
652
Christopher Tate22b87872009-05-04 16:41:53 -0700653 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700654 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700655 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700656 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700657 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800658 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800659 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800660 // If Encrypted file systems is enabled or disabled, this call will return the
661 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600662 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800663 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700664 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700665
Christopher Tate2efd2db2011-07-19 16:32:49 -0700666 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
667 if (mPasswordHashFile.exists()) {
668 FileInputStream fin = null;
669 DataInputStream in = null;
670 try {
671 fin = new FileInputStream(mPasswordHashFile);
672 in = new DataInputStream(new BufferedInputStream(fin));
673 // integer length of the salt array, followed by the salt,
674 // then the hex pw hash string
675 int saltLen = in.readInt();
676 byte[] salt = new byte[saltLen];
677 in.readFully(salt);
678 mPasswordHash = in.readUTF();
679 mPasswordSalt = salt;
680 } catch (IOException e) {
681 Slog.e(TAG, "Unable to read saved backup pw hash");
682 } finally {
683 try {
684 if (in != null) in.close();
685 if (fin != null) fin.close();
686 } catch (IOException e) {
687 Slog.w(TAG, "Unable to close streams");
688 }
689 }
690 }
691
Christopher Tate4cc86e12009-09-21 19:36:51 -0700692 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700693 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700694 IntentFilter filter = new IntentFilter();
695 filter.addAction(RUN_BACKUP_ACTION);
696 context.registerReceiver(mRunBackupReceiver, filter,
697 android.Manifest.permission.BACKUP, null);
698
699 mRunInitReceiver = new RunInitializeReceiver();
700 filter = new IntentFilter();
701 filter.addAction(RUN_INITIALIZE_ACTION);
702 context.registerReceiver(mRunInitReceiver, filter,
703 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700704
705 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700706 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
707 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
708
Christopher Tate4cc86e12009-09-21 19:36:51 -0700709 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
710 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
711 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
712
Christopher Tatecde87f42009-06-12 12:55:53 -0700713 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700714 mJournalDir = new File(mBaseStateDir, "pending");
715 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700716 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700717
Christopher Tate73e02522009-07-15 14:18:26 -0700718 // Set up the various sorts of package tracking we do
719 initPackageTracking();
720
Christopher Tateabce4e82009-06-18 18:35:32 -0700721 // Build our mapping of uid to backup client services. This implicitly
722 // schedules a backup pass on the Package Manager metadata the first
723 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700724 synchronized (mBackupParticipants) {
725 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700726 }
727
Dan Egnor87a02bc2009-06-17 02:30:10 -0700728 // Set up our transport options and initialize the default transport
729 // TODO: Have transports register themselves somehow?
730 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700731 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700732 ComponentName localName = new ComponentName(context, LocalTransport.class);
733 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700734
Christopher Tate91717492009-06-26 21:07:13 -0700735 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700736 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
737 Settings.Secure.BACKUP_TRANSPORT);
738 if ("".equals(mCurrentTransport)) {
739 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700740 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800741 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700742
743 // Attach to the Google backup transport. When this comes up, it will set
744 // itself as the current transport because we explicitly reset mCurrentTransport
745 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700746 ComponentName transportComponent = new ComponentName("com.google.android.backup",
747 "com.google.android.backup.BackupTransportService");
748 try {
749 // If there's something out there that is supposed to be the Google
750 // backup transport, make sure it's legitimately part of the OS build
751 // and not an app lying about its package name.
752 ApplicationInfo info = mPackageManager.getApplicationInfo(
753 transportComponent.getPackageName(), 0);
754 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
755 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
756 Intent intent = new Intent().setComponent(transportComponent);
757 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
758 } else {
759 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
760 }
761 } catch (PackageManager.NameNotFoundException nnf) {
762 // No such package? No binding.
763 if (DEBUG) Slog.v(TAG, "Google transport not present");
764 }
Christopher Tateaa088442009-06-16 18:25:46 -0700765
Christopher Tatecde87f42009-06-12 12:55:53 -0700766 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700767 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700768 parseLeftoverJournals();
769
Christopher Tateb6787f22009-07-02 17:40:45 -0700770 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700771 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700772
773 // Start the backup passes going
774 setBackupEnabled(areEnabled);
775 }
776
777 private class RunBackupReceiver extends BroadcastReceiver {
778 public void onReceive(Context context, Intent intent) {
779 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700780 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700781 if (mPendingInits.size() > 0) {
782 // If there are pending init operations, we process those
783 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800784 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700785 try {
786 mAlarmManager.cancel(mRunInitIntent);
787 mRunInitIntent.send();
788 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800789 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700790 // can't really do more than bail here
791 }
792 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800793 // Don't run backups now if we're disabled or not yet
794 // fully set up.
795 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800796 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700797
798 // Acquire the wakelock and pass it to the backup thread. it will
799 // be released once backup concludes.
800 mWakelock.acquire();
801
802 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
803 mBackupHandler.sendMessage(msg);
804 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800805 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700806 }
807 }
808 }
809 }
810 }
811 }
812
813 private class RunInitializeReceiver extends BroadcastReceiver {
814 public void onReceive(Context context, Intent intent) {
815 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
816 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800817 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700818
819 // Acquire the wakelock and pass it to the init thread. it will
820 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700821 mWakelock.acquire();
822
Christopher Tate4cc86e12009-09-21 19:36:51 -0700823 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700824 mBackupHandler.sendMessage(msg);
825 }
826 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700827 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700828 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700829
Christopher Tate73e02522009-07-15 14:18:26 -0700830 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800831 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700832
Christopher Tate84725812010-02-04 15:52:40 -0800833 // Remember our ancestral dataset
834 mTokenFile = new File(mBaseStateDir, "ancestral");
835 try {
836 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800837 int version = tf.readInt();
838 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
839 mAncestralToken = tf.readLong();
840 mCurrentToken = tf.readLong();
841
842 int numPackages = tf.readInt();
843 if (numPackages >= 0) {
844 mAncestralPackages = new HashSet<String>();
845 for (int i = 0; i < numPackages; i++) {
846 String pkgName = tf.readUTF();
847 mAncestralPackages.add(pkgName);
848 }
849 }
850 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800851 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800852 } catch (FileNotFoundException fnf) {
853 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800854 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800855 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800856 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800857 }
858
Christopher Tatee97e8072009-07-15 16:45:50 -0700859 // Keep a log of what apps we've ever backed up. Because we might have
860 // rebooted in the middle of an operation that was removing something from
861 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700862 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700863 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700864
Christopher Tatee97e8072009-07-15 16:45:50 -0700865 // If we were in the middle of removing something from the ever-backed-up
866 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700867 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700868 if (tempProcessedFile.exists()) {
869 tempProcessedFile.delete();
870 }
871
Dan Egnor852f8e42009-09-30 11:20:45 -0700872 // If there are previous contents, parse them out then start a new
873 // file to continue the recordkeeping.
874 if (mEverStored.exists()) {
875 RandomAccessFile temp = null;
876 RandomAccessFile in = null;
877
878 try {
879 temp = new RandomAccessFile(tempProcessedFile, "rws");
880 in = new RandomAccessFile(mEverStored, "r");
881
882 while (true) {
883 PackageInfo info;
884 String pkg = in.readUTF();
885 try {
886 info = mPackageManager.getPackageInfo(pkg, 0);
887 mEverStoredApps.add(pkg);
888 temp.writeUTF(pkg);
Christopher Tatec58efa62011-08-01 19:20:14 -0700889 if (MORE_DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700890 } catch (NameNotFoundException e) {
891 // nope, this package was uninstalled; don't include it
Christopher Tatec58efa62011-08-01 19:20:14 -0700892 if (MORE_DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700893 }
894 }
895 } catch (EOFException e) {
896 // Once we've rewritten the backup history log, atomically replace the
897 // old one with the new one then reopen the file for continuing use.
898 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800899 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700900 }
901 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800902 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700903 } finally {
904 try { if (temp != null) temp.close(); } catch (IOException e) {}
905 try { if (in != null) in.close(); } catch (IOException e) {}
906 }
907 }
908
Christopher Tate73e02522009-07-15 14:18:26 -0700909 // Register for broadcasts about package install, etc., so we can
910 // update the provider list.
911 IntentFilter filter = new IntentFilter();
912 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
913 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Christopher Tatecc55f812011-08-16 16:06:53 -0700914 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Christopher Tate73e02522009-07-15 14:18:26 -0700915 filter.addDataScheme("package");
916 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800917 // Register for events related to sdcard installation.
918 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800919 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
920 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800921 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700922 }
923
Christopher Tatecde87f42009-06-12 12:55:53 -0700924 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700925 for (File f : mJournalDir.listFiles()) {
926 if (mJournal == null || f.compareTo(mJournal) != 0) {
927 // This isn't the current journal, so it must be a leftover. Read
928 // out the package names mentioned there and schedule them for
929 // backup.
930 RandomAccessFile in = null;
931 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400932 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700933 in = new RandomAccessFile(f, "r");
934 while (true) {
935 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400936 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700937 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700938 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700939 } catch (EOFException e) {
940 // no more data; we're done
941 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800942 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700943 } finally {
944 // close/delete the file
945 try { if (in != null) in.close(); } catch (IOException e) {}
946 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700947 }
948 }
949 }
950 }
951
Christopher Tate2efd2db2011-07-19 16:32:49 -0700952 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
953 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
954 }
955
956 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
957 try {
958 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
959 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
960 return keyFactory.generateSecret(ks);
961 } catch (InvalidKeySpecException e) {
962 Slog.e(TAG, "Invalid key spec for PBKDF2!");
963 } catch (NoSuchAlgorithmException e) {
964 Slog.e(TAG, "PBKDF2 unavailable!");
965 }
966 return null;
967 }
968
969 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
970 SecretKey key = buildPasswordKey(pw, salt, rounds);
971 if (key != null) {
972 return byteArrayToHex(key.getEncoded());
973 }
974 return null;
975 }
976
977 private String byteArrayToHex(byte[] data) {
978 StringBuilder buf = new StringBuilder(data.length * 2);
979 for (int i = 0; i < data.length; i++) {
980 buf.append(Byte.toHexString(data[i], true));
981 }
982 return buf.toString();
983 }
984
985 private byte[] hexToByteArray(String digits) {
986 final int bytes = digits.length() / 2;
987 if (2*bytes != digits.length()) {
988 throw new IllegalArgumentException("Hex string must have an even number of digits");
989 }
990
991 byte[] result = new byte[bytes];
992 for (int i = 0; i < digits.length(); i += 2) {
993 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
994 }
995 return result;
996 }
997
998 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
999 char[] mkAsChar = new char[pwBytes.length];
1000 for (int i = 0; i < pwBytes.length; i++) {
1001 mkAsChar[i] = (char) pwBytes[i];
1002 }
1003
1004 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
1005 return checksum.getEncoded();
1006 }
1007
1008 // Used for generating random salts or passwords
1009 private byte[] randomBytes(int bits) {
1010 byte[] array = new byte[bits / 8];
1011 mRng.nextBytes(array);
1012 return array;
1013 }
1014
1015 // Backup password management
1016 boolean passwordMatchesSaved(String candidatePw, int rounds) {
1017 if (mPasswordHash == null) {
1018 // no current password case -- require that 'currentPw' be null or empty
1019 if (candidatePw == null || "".equals(candidatePw)) {
1020 return true;
1021 } // else the non-empty candidate does not match the empty stored pw
1022 } else {
1023 // hash the stated current pw and compare to the stored one
1024 if (candidatePw != null && candidatePw.length() > 0) {
1025 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
1026 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
1027 // candidate hash matches the stored hash -- the password matches
1028 return true;
1029 }
1030 } // else the stored pw is nonempty but the candidate is empty; no match
1031 }
1032 return false;
1033 }
1034
1035 @Override
1036 public boolean setBackupPassword(String currentPw, String newPw) {
1037 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1038 "setBackupPassword");
1039
1040 // If the supplied pw doesn't hash to the the saved one, fail
1041 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1042 return false;
1043 }
1044
1045 // Clearing the password is okay
1046 if (newPw == null || newPw.isEmpty()) {
1047 if (mPasswordHashFile.exists()) {
1048 if (!mPasswordHashFile.delete()) {
1049 // Unable to delete the old pw file, so fail
1050 Slog.e(TAG, "Unable to clear backup password");
1051 return false;
1052 }
1053 }
1054 mPasswordHash = null;
1055 mPasswordSalt = null;
1056 return true;
1057 }
1058
1059 try {
1060 // Okay, build the hash of the new backup password
1061 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1062 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1063
1064 OutputStream pwf = null, buffer = null;
1065 DataOutputStream out = null;
1066 try {
1067 pwf = new FileOutputStream(mPasswordHashFile);
1068 buffer = new BufferedOutputStream(pwf);
1069 out = new DataOutputStream(buffer);
1070 // integer length of the salt array, followed by the salt,
1071 // then the hex pw hash string
1072 out.writeInt(salt.length);
1073 out.write(salt);
1074 out.writeUTF(newPwHash);
1075 out.flush();
1076 mPasswordHash = newPwHash;
1077 mPasswordSalt = salt;
1078 return true;
1079 } finally {
1080 if (out != null) out.close();
1081 if (buffer != null) buffer.close();
1082 if (pwf != null) pwf.close();
1083 }
1084 } catch (IOException e) {
1085 Slog.e(TAG, "Unable to set backup password");
1086 }
1087 return false;
1088 }
1089
1090 @Override
1091 public boolean hasBackupPassword() {
1092 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1093 "hasBackupPassword");
1094 return (mPasswordHash != null && mPasswordHash.length() > 0);
1095 }
1096
Christopher Tate4cc86e12009-09-21 19:36:51 -07001097 // Maintain persistent state around whether need to do an initialize operation.
1098 // Must be called with the queue lock held.
1099 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001100 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001101 + " on transport " + transportName);
1102 try {
1103 IBackupTransport transport = getTransport(transportName);
1104 String transportDirName = transport.transportDirName();
1105 File stateDir = new File(mBaseStateDir, transportDirName);
1106 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1107
1108 if (isPending) {
1109 // We need an init before we can proceed with sending backup data.
1110 // Record that with an entry in our set of pending inits, as well as
1111 // journaling it via creation of a sentinel file.
1112 mPendingInits.add(transportName);
1113 try {
1114 (new FileOutputStream(initPendingFile)).close();
1115 } catch (IOException ioe) {
1116 // Something is badly wrong with our permissions; just try to move on
1117 }
1118 } else {
1119 // No more initialization needed; wipe the journal and reset our state.
1120 initPendingFile.delete();
1121 mPendingInits.remove(transportName);
1122 }
1123 } catch (RemoteException e) {
1124 // can't happen; the transport is local
1125 }
1126 }
1127
Christopher Tated55e18a2009-09-21 10:12:59 -07001128 // Reset all of our bookkeeping, in response to having been told that
1129 // the backend data has been wiped [due to idle expiry, for example],
1130 // so we must re-upload all saved settings.
1131 void resetBackupState(File stateFileDir) {
1132 synchronized (mQueueLock) {
1133 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001134 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001135 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001136
Christopher Tate84725812010-02-04 15:52:40 -08001137 mCurrentToken = 0;
1138 writeRestoreTokens();
1139
Christopher Tated55e18a2009-09-21 10:12:59 -07001140 // Remove all the state files
1141 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001142 // ... but don't touch the needs-init sentinel
1143 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1144 sf.delete();
1145 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001146 }
Christopher Tate45597642011-04-04 16:59:21 -07001147 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001148
Christopher Tate45597642011-04-04 16:59:21 -07001149 // Enqueue a new backup of every participant
Christopher Tate8e294d42011-08-31 20:37:12 -07001150 synchronized (mBackupParticipants) {
1151 int N = mBackupParticipants.size();
1152 for (int i=0; i<N; i++) {
1153 int uid = mBackupParticipants.keyAt(i);
1154 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1155 for (ApplicationInfo app: participants) {
1156 dataChangedImpl(app.packageName);
1157 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001158 }
1159 }
1160 }
1161
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001162 // Add a transport to our set of available backends. If 'transport' is null, this
1163 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001164 private void registerTransport(String name, IBackupTransport transport) {
1165 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001166 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001167 if (transport != null) {
1168 mTransports.put(name, transport);
1169 } else {
1170 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001171 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001172 mCurrentTransport = null;
1173 }
1174 // Nothing further to do in the unregistration case
1175 return;
1176 }
Christopher Tate91717492009-06-26 21:07:13 -07001177 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001178
1179 // If the init sentinel file exists, we need to be sure to perform the init
1180 // as soon as practical. We also create the state directory at registration
1181 // time to ensure it's present from the outset.
1182 try {
1183 String transportName = transport.transportDirName();
1184 File stateDir = new File(mBaseStateDir, transportName);
1185 stateDir.mkdirs();
1186
1187 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1188 if (initSentinel.exists()) {
1189 synchronized (mQueueLock) {
1190 mPendingInits.add(transportName);
1191
1192 // TODO: pick a better starting time than now + 1 minute
1193 long delay = 1000 * 60; // one minute, in milliseconds
1194 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1195 System.currentTimeMillis() + delay, mRunInitIntent);
1196 }
1197 }
1198 } catch (RemoteException e) {
1199 // can't happen, the transport is local
1200 }
Christopher Tate91717492009-06-26 21:07:13 -07001201 }
1202
Christopher Tate3799bc22009-05-06 16:13:56 -07001203 // ----- Track installation/removal of packages -----
1204 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1205 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001206 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001207
Christopher Tate3799bc22009-05-06 16:13:56 -07001208 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001209 boolean replacing = false;
1210 boolean added = false;
1211 Bundle extras = intent.getExtras();
1212 String pkgList[] = null;
1213 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
Christopher Tatecc55f812011-08-16 16:06:53 -07001214 Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
1215 Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001216 Uri uri = intent.getData();
1217 if (uri == null) {
1218 return;
1219 }
1220 String pkgName = uri.getSchemeSpecificPart();
1221 if (pkgName != null) {
1222 pkgList = new String[] { pkgName };
1223 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001224 if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
1225 // use the existing "add with replacement" logic
1226 if (MORE_DEBUG) Slog.d(TAG, "PACKAGE_REPLACED, updating package " + pkgName);
1227 added = replacing = true;
1228 } else {
1229 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1230 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
1231 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001232 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001233 added = true;
1234 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001235 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001236 added = false;
1237 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1238 }
Christopher Tatecc55f812011-08-16 16:06:53 -07001239
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001240 if (pkgList == null || pkgList.length == 0) {
1241 return;
1242 }
1243 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001244 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001245 for (String pkgName : pkgList) {
1246 if (replacing) {
1247 // The package was just upgraded
1248 updatePackageParticipantsLocked(pkgName);
1249 } else {
1250 // The package was just added
1251 addPackageParticipantsLocked(pkgName);
1252 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001253 }
1254 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001255 } else {
1256 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001257 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1258 } else {
1259 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001260 for (String pkgName : pkgList) {
1261 removePackageParticipantsLocked(pkgName);
1262 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001263 }
1264 }
1265 }
1266 }
1267 };
1268
Dan Egnor87a02bc2009-06-17 02:30:10 -07001269 // ----- Track connection to GoogleBackupTransport service -----
1270 ServiceConnection mGoogleConnection = new ServiceConnection() {
1271 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001272 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001273 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001274 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001275 }
1276
1277 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001278 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001279 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001280 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001281 }
1282 };
1283
Christopher Tate181fafa2009-05-14 11:12:14 -07001284 // Add the backup agents in the given package to our set of known backup participants.
1285 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001286 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001287 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001288 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001289 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001290 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001291 }
1292
Christopher Tate181fafa2009-05-14 11:12:14 -07001293 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001294 List<PackageInfo> targetPkgs) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001295 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001296 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001297 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001298 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001299 + " uid=" + p.applicationInfo.uid
1300 + " killAfterRestore="
1301 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001302 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001303 }
1304 }
1305
Dan Egnorefe52642009-06-24 00:16:33 -07001306 for (PackageInfo pkg : targetPkgs) {
1307 if (packageName == null || pkg.packageName.equals(packageName)) {
1308 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001309 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001310 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001311 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001312 mBackupParticipants.put(uid, set);
1313 }
Dan Egnorefe52642009-06-24 00:16:33 -07001314 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001315
1316 // If we've never seen this app before, schedule a backup for it
1317 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001318 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001319 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001320 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001321 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001322 }
Christopher Tate487529a2009-04-29 14:03:25 -07001323 }
1324 }
1325
Christopher Tate6785dd82009-06-18 15:58:25 -07001326 // Remove the given package's entry from our known active set. If
1327 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001328 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001329 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001330 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001331 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001332 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001333 } else {
1334 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001335 List<PackageInfo> knownPackages = allAgentPackages();
1336 for (PackageInfo pkg : knownPackages) {
1337 allApps.add(pkg.packageName);
1338 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001339 }
1340 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001341 }
1342
Joe Onorato8ad02812009-05-13 01:41:44 -04001343 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001344 List<String> allPackageNames) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001345 if (MORE_DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001346 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001347 + ") removing " + allPackageNames.size() + " entries");
1348 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001349 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001350 }
1351 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001352 for (String pkg : allPackageNames) {
1353 if (packageName == null || pkg.equals(packageName)) {
1354 int uid = -1;
1355 try {
1356 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1357 uid = info.applicationInfo.uid;
1358 } catch (NameNotFoundException e) {
1359 // we don't know this package name, so just skip it for now
1360 continue;
1361 }
1362
Christopher Tate181fafa2009-05-14 11:12:14 -07001363 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001364 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001365 // Find the existing entry with the same package name, and remove it.
1366 // We can't just remove(app) because the instances are different.
1367 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001368 if (entry.packageName.equals(pkg)) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001369 if (MORE_DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001370 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001371 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001372 break;
1373 }
1374 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001375 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001376 mBackupParticipants.delete(uid);
1377 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001378 }
1379 }
1380 }
1381 }
1382
Christopher Tate181fafa2009-05-14 11:12:14 -07001383 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001384 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001385 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001386 int flags = PackageManager.GET_SIGNATURES;
1387 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1388 int N = packages.size();
1389 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001390 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001391 try {
1392 ApplicationInfo app = pkg.applicationInfo;
1393 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001394 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001395 packages.remove(a);
1396 }
1397 else {
1398 // we will need the shared library path, so look that up and store it here
1399 app = mPackageManager.getApplicationInfo(pkg.packageName,
1400 PackageManager.GET_SHARED_LIBRARY_FILES);
1401 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1402 }
1403 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001404 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001405 }
1406 }
Dan Egnorefe52642009-06-24 00:16:33 -07001407 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001408 }
Christopher Tateaa088442009-06-16 18:25:46 -07001409
Christopher Tate3799bc22009-05-06 16:13:56 -07001410 // Reset the given package's known backup participants. Unlike add/remove, the update
1411 // action cannot be passed a null package name.
1412 void updatePackageParticipantsLocked(String packageName) {
1413 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001414 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001415 return;
1416 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001417 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001418
1419 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001420 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001421 List<String> allAppNames = new ArrayList<String>();
1422 for (PackageInfo pkg : allApps) {
1423 allAppNames.add(pkg.packageName);
1424 }
1425 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001426 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001427 }
1428
Christopher Tate84725812010-02-04 15:52:40 -08001429 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001430 // backed up at least once
1431 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001432 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1433
1434 synchronized (mEverStoredApps) {
1435 if (!mEverStoredApps.add(packageName)) return;
1436
1437 RandomAccessFile out = null;
1438 try {
1439 out = new RandomAccessFile(mEverStored, "rws");
1440 out.seek(out.length());
1441 out.writeUTF(packageName);
1442 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001443 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001444 } finally {
1445 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001446 }
1447 }
1448 }
1449
Christopher Tatee97e8072009-07-15 16:45:50 -07001450 // Remove our awareness of having ever backed up the given package
1451 void removeEverBackedUp(String packageName) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001452 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName);
1453 if (MORE_DEBUG) Slog.v(TAG, "New set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001454
Dan Egnor852f8e42009-09-30 11:20:45 -07001455 synchronized (mEverStoredApps) {
1456 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1457 // we'll recognize on initialization time that the package no longer
1458 // exists and fix it up then.
1459 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1460 RandomAccessFile known = null;
1461 try {
1462 known = new RandomAccessFile(tempKnownFile, "rws");
1463 mEverStoredApps.remove(packageName);
1464 for (String s : mEverStoredApps) {
1465 known.writeUTF(s);
Christopher Tatec58efa62011-08-01 19:20:14 -07001466 if (MORE_DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001467 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001468 known.close();
1469 known = null;
1470 if (!tempKnownFile.renameTo(mEverStored)) {
1471 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1472 }
1473 } catch (IOException e) {
1474 // Bad: we couldn't create the new copy. For safety's sake we
1475 // abandon the whole process and remove all what's-backed-up
1476 // state entirely, meaning we'll force a backup pass for every
1477 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001478 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001479 mEverStoredApps.clear();
1480 tempKnownFile.delete();
1481 mEverStored.delete();
1482 } finally {
1483 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001484 }
1485 }
1486 }
1487
Christopher Tateb49ceb32010-02-08 16:22:24 -08001488 // Persistently record the current and ancestral backup tokens as well
1489 // as the set of packages with data [supposedly] available in the
1490 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001491 void writeRestoreTokens() {
1492 try {
1493 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001494
1495 // First, the version number of this record, for futureproofing
1496 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1497
1498 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001499 af.writeLong(mAncestralToken);
1500 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001501
1502 // Now write the set of ancestral packages
1503 if (mAncestralPackages == null) {
1504 af.writeInt(-1);
1505 } else {
1506 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001507 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001508 for (String pkgName : mAncestralPackages) {
1509 af.writeUTF(pkgName);
Christopher Tatec58efa62011-08-01 19:20:14 -07001510 if (MORE_DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001511 }
1512 }
Christopher Tate84725812010-02-04 15:52:40 -08001513 af.close();
1514 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001515 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001516 }
1517 }
1518
Dan Egnor87a02bc2009-06-17 02:30:10 -07001519 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001520 private IBackupTransport getTransport(String transportName) {
1521 synchronized (mTransports) {
1522 IBackupTransport transport = mTransports.get(transportName);
1523 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001524 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001525 }
1526 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001527 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001528 }
1529
Christopher Tatedf01dea2009-06-09 20:45:02 -07001530 // fire off a backup agent, blocking until it attaches or times out
1531 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1532 IBackupAgent agent = null;
1533 synchronized(mAgentConnectLock) {
1534 mConnecting = true;
1535 mConnectedAgent = null;
1536 try {
1537 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001538 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001539
1540 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001541 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001542 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1543 while (mConnecting && mConnectedAgent == null
1544 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001545 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001546 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001547 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001548 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001549 return null;
1550 }
1551 }
1552
1553 // if we timed out with no connect, abort and move on
1554 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001556 return null;
1557 }
1558 agent = mConnectedAgent;
1559 }
1560 } catch (RemoteException e) {
1561 // can't happen
1562 }
1563 }
1564 return agent;
1565 }
1566
Christopher Tatec7b31e32009-06-10 15:49:30 -07001567 // clear an application's data, blocking until the operation completes or times out
1568 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001569 // Don't wipe packages marked allowClearUserData=false
1570 try {
1571 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1572 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Christopher Tatec58efa62011-08-01 19:20:14 -07001573 if (MORE_DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001574 + packageName);
1575 return;
1576 }
1577 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001578 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001579 return;
1580 }
1581
Christopher Tatec7b31e32009-06-10 15:49:30 -07001582 ClearDataObserver observer = new ClearDataObserver();
1583
1584 synchronized(mClearDataLock) {
1585 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001586 try {
1587 mActivityManager.clearApplicationUserData(packageName, observer);
1588 } catch (RemoteException e) {
1589 // can't happen because the activity manager is in this process
1590 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001591
1592 // only wait 10 seconds for the clear data to happen
1593 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1594 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1595 try {
1596 mClearDataLock.wait(5000);
1597 } catch (InterruptedException e) {
1598 // won't happen, but still.
1599 mClearingData = false;
1600 }
1601 }
1602 }
1603 }
1604
1605 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001606 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001607 synchronized(mClearDataLock) {
1608 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001609 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001610 }
1611 }
1612 }
1613
Christopher Tate1bb69062010-02-19 17:02:12 -08001614 // Get the restore-set token for the best-available restore set for this package:
1615 // the active set if possible, else the ancestral one. Returns zero if none available.
1616 long getAvailableRestoreToken(String packageName) {
1617 long token = mAncestralToken;
1618 synchronized (mQueueLock) {
1619 if (mEverStoredApps.contains(packageName)) {
1620 token = mCurrentToken;
1621 }
1622 }
1623 return token;
1624 }
1625
Christopher Tate44a27902010-01-27 17:15:49 -08001626 // -----
Christopher Tate8e294d42011-08-31 20:37:12 -07001627 // Interface and methods used by the asynchronous-with-timeout backup/restore operations
1628
1629 interface BackupRestoreTask {
1630 // Execute one tick of whatever state machine the task implements
1631 void execute();
1632
1633 // An operation that wanted a callback has completed
1634 void operationComplete();
1635
1636 // An operation that wanted a callback has timed out
1637 void handleTimeout();
1638 }
1639
1640 void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback) {
1641 if (MORE_DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
1642 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001643 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001644 mCurrentOperations.put(token, new Operation(OP_PENDING, callback));
1645
1646 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0, callback);
1647 mBackupHandler.sendMessageDelayed(msg, interval);
1648 }
1649 }
1650
1651 // synchronous waiter case
1652 boolean waitUntilOperationComplete(int token) {
1653 if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
1654 + Integer.toHexString(token));
1655 int finalState = OP_PENDING;
1656 Operation op = null;
1657 synchronized (mCurrentOpLock) {
1658 while (true) {
1659 op = mCurrentOperations.get(token);
1660 if (op == null) {
1661 // mysterious disappearance: treat as success with no callback
1662 break;
1663 } else {
1664 if (op.state == OP_PENDING) {
1665 try {
1666 mCurrentOpLock.wait();
1667 } catch (InterruptedException e) {}
1668 // When the wait is notified we loop around and recheck the current state
1669 } else {
1670 // No longer pending; we're done
1671 finalState = op.state;
1672 break;
1673 }
Christopher Tate44a27902010-01-27 17:15:49 -08001674 }
Christopher Tate44a27902010-01-27 17:15:49 -08001675 }
1676 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001677
Christopher Tate44a27902010-01-27 17:15:49 -08001678 mBackupHandler.removeMessages(MSG_TIMEOUT);
Christopher Tatec58efa62011-08-01 19:20:14 -07001679 if (MORE_DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001680 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001681 return finalState == OP_ACKNOWLEDGED;
1682 }
1683
Christopher Tate8e294d42011-08-31 20:37:12 -07001684 void handleTimeout(int token, Object obj) {
1685 // Notify any synchronous waiters
1686 Operation op = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07001687 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001688 op = mCurrentOperations.get(token);
1689 if (MORE_DEBUG) {
1690 if (op == null) Slog.w(TAG, "Timeout of token " + Integer.toHexString(token)
1691 + " but no op found");
1692 }
1693 int state = (op != null) ? op.state : OP_TIMEOUT;
1694 if (state == OP_PENDING) {
1695 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + Integer.toHexString(token));
1696 op.state = OP_TIMEOUT;
1697 mCurrentOperations.put(token, op);
1698 }
1699 mCurrentOpLock.notifyAll();
1700 }
1701
1702 // If there's a TimeoutHandler for this event, call it
1703 if (op != null && op.callback != null) {
1704 op.callback.handleTimeout();
Christopher Tate4a627c72011-04-01 14:43:32 -07001705 }
Christopher Tate44a27902010-01-27 17:15:49 -08001706 }
1707
Christopher Tate043dadc2009-06-02 16:11:00 -07001708 // ----- Back up a set of applications via a worker thread -----
1709
Christopher Tate8e294d42011-08-31 20:37:12 -07001710 enum BackupState {
1711 INITIAL,
1712 RUNNING_QUEUE,
1713 FINAL
1714 }
1715
1716 class PerformBackupTask implements BackupRestoreTask {
1717 private static final String TAG = "PerformBackupTask";
1718
Christopher Tateaa088442009-06-16 18:25:46 -07001719 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001720 ArrayList<BackupRequest> mQueue;
Christopher Tate8e294d42011-08-31 20:37:12 -07001721 ArrayList<BackupRequest> mOriginalQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001722 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001723 File mJournal;
Christopher Tate8e294d42011-08-31 20:37:12 -07001724 BackupState mCurrentState;
1725
1726 // carried information about the current in-flight operation
1727 PackageInfo mCurrentPackage;
1728 File mSavedStateName;
1729 File mBackupDataName;
1730 File mNewStateName;
1731 ParcelFileDescriptor mSavedState;
1732 ParcelFileDescriptor mBackupData;
1733 ParcelFileDescriptor mNewState;
1734 int mStatus;
1735 boolean mFinished;
Christopher Tate043dadc2009-06-02 16:11:00 -07001736
Christopher Tate44a27902010-01-27 17:15:49 -08001737 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001738 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001739 mTransport = transport;
Christopher Tate8e294d42011-08-31 20:37:12 -07001740 mOriginalQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001741 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001742
1743 try {
1744 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1745 } catch (RemoteException e) {
1746 // can't happen; the transport is local
1747 }
Christopher Tate8e294d42011-08-31 20:37:12 -07001748
1749 mCurrentState = BackupState.INITIAL;
1750 mFinished = false;
Christopher Tate043dadc2009-06-02 16:11:00 -07001751 }
1752
Christopher Tate8e294d42011-08-31 20:37:12 -07001753 // Main entry point: perform one chunk of work, updating the state as appropriate
1754 // and reposting the next chunk to the primary backup handler thread.
1755 @Override
1756 public void execute() {
1757 switch (mCurrentState) {
1758 case INITIAL:
1759 beginBackup();
1760 break;
1761
1762 case RUNNING_QUEUE:
1763 invokeNextAgent();
1764 break;
1765
1766 case FINAL:
1767 if (!mFinished) finalizeBackup();
1768 else {
1769 Slog.e(TAG, "Duplicate finish");
1770 }
Christopher Tate2982d062011-09-06 20:35:24 -07001771 mFinished = true;
Christopher Tate8e294d42011-08-31 20:37:12 -07001772 break;
1773 }
1774 }
1775
1776 // We're starting a backup pass. Initialize the transport and send
1777 // the PM metadata blob if we haven't already.
1778 void beginBackup() {
1779 mStatus = BackupConstants.TRANSPORT_OK;
1780
1781 // Sanity check: if the queue is empty we have no work to do.
1782 if (mOriginalQueue.isEmpty()) {
1783 Slog.w(TAG, "Backup begun with an empty queue - nothing to do.");
1784 return;
1785 }
1786
1787 // We need to retain the original queue contents in case of transport
1788 // failure, but we want a working copy that we can manipulate along
1789 // the way.
1790 mQueue = (ArrayList<BackupRequest>) mOriginalQueue.clone();
1791
Joe Onorato8a9b2202010-02-26 18:56:32 -08001792 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001793
Christopher Tate8e294d42011-08-31 20:37:12 -07001794 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
Christopher Tate043dadc2009-06-02 16:11:00 -07001795 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001796 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001797
Dan Egnor852f8e42009-09-30 11:20:45 -07001798 // If we haven't stored package manager metadata yet, we must init the transport.
Christopher Tate8e294d42011-08-31 20:37:12 -07001799 if (mStatus == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001800 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001801 resetBackupState(mStateDir); // Just to make sure.
Christopher Tate8e294d42011-08-31 20:37:12 -07001802 mStatus = mTransport.initializeDevice();
1803 if (mStatus == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001804 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001805 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001806 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001807 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001808 }
Dan Egnor01445162009-09-21 17:04:05 -07001809 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001810
1811 // The package manager doesn't have a proper <application> etc, but since
1812 // it's running here in the system process we can just set up its agent
1813 // directly and use a synthetic BackupRequest. We always run this pass
1814 // because it's cheap and this way we guarantee that we don't get out of
1815 // step even if we're selecting among various transports at run time.
Christopher Tate8e294d42011-08-31 20:37:12 -07001816 if (mStatus == BackupConstants.TRANSPORT_OK) {
Dan Egnor01445162009-09-21 17:04:05 -07001817 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1818 mPackageManager, allAgentPackages());
Christopher Tate8e294d42011-08-31 20:37:12 -07001819 mStatus = invokeAgentForBackup(PACKAGE_MANAGER_SENTINEL,
Dan Egnor01445162009-09-21 17:04:05 -07001820 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1821 }
Christopher Tate90967f42009-09-20 15:28:33 -07001822
Christopher Tate8e294d42011-08-31 20:37:12 -07001823 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1824 // The backend reports that our dataset has been wiped. Note this in
1825 // the event log; the no-success code below will reset the backup
1826 // state as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001827 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001828 }
1829 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001830 Slog.e(TAG, "Error in backup thread", e);
Christopher Tate8e294d42011-08-31 20:37:12 -07001831 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001832 } finally {
Christopher Tate8e294d42011-08-31 20:37:12 -07001833 // If we've succeeded so far, invokeAgentForBackup() will have run the PM
1834 // metadata and its completion/timeout callback will continue the state
1835 // machine chain. If it failed that won't happen; we handle that now.
1836 if (mStatus != BackupConstants.TRANSPORT_OK) {
1837 // if things went wrong at this point, we need to
1838 // restage everything and try again later.
1839 resetBackupState(mStateDir); // Just to make sure.
1840 executeNextState(BackupState.FINAL);
Christopher Tate84725812010-02-04 15:52:40 -08001841 }
Christopher Tatecde87f42009-06-12 12:55:53 -07001842 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001843 }
1844
Christopher Tate8e294d42011-08-31 20:37:12 -07001845 // Transport has been initialized and the PM metadata submitted successfully
1846 // if that was warranted. Now we process the single next thing in the queue.
1847 void invokeNextAgent() {
1848 mStatus = BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001849
Christopher Tate8e294d42011-08-31 20:37:12 -07001850 // Sanity check that we have work to do. If not, skip to the end where
1851 // we reestablish the wakelock invariants etc.
1852 if (mQueue.isEmpty()) {
1853 Slog.e(TAG, "Running queue but it's empty!");
1854 executeNextState(BackupState.FINAL);
1855 return;
1856 }
1857
1858 // pop the entry we're going to process on this step
1859 BackupRequest request = mQueue.get(0);
1860 mQueue.remove(0);
1861
1862 Slog.d(TAG, "starting agent for backup of " + request);
1863
1864 // Verify that the requested app exists; it might be something that
1865 // requested a backup but was then uninstalled. The request was
1866 // journalled and rather than tamper with the journal it's safer
1867 // to sanity-check here. This also gives us the classname of the
1868 // package's backup agent.
1869 try {
1870 mCurrentPackage = mPackageManager.getPackageInfo(request.packageName,
1871 PackageManager.GET_SIGNATURES);
Christopher Tatec28083a2010-12-14 16:16:44 -08001872
Christopher Tate043dadc2009-06-02 16:11:00 -07001873 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001874 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07001875 mWakelock.setWorkSource(new WorkSource(mCurrentPackage.applicationInfo.uid));
1876 agent = bindToAgentSynchronous(mCurrentPackage.applicationInfo,
Christopher Tate4a627c72011-04-01 14:43:32 -07001877 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001878 if (agent != null) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001879 mStatus = invokeAgentForBackup(request.packageName, agent, mTransport);
1880 // at this point we'll either get a completion callback from the
1881 // agent, or a timeout message on the main handler. either way, we're
1882 // done here as long as we're successful so far.
1883 } else {
1884 // Timeout waiting for the agent
1885 mStatus = BackupConstants.AGENT_ERROR;
Christopher Tate043dadc2009-06-02 16:11:00 -07001886 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001887 } catch (SecurityException ex) {
1888 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001889 Slog.d(TAG, "error in bind/backup", ex);
Christopher Tate8e294d42011-08-31 20:37:12 -07001890 mStatus = BackupConstants.AGENT_ERROR;
1891 }
1892 } catch (NameNotFoundException e) {
1893 Slog.d(TAG, "Package does not exist; skipping");
1894 } finally {
1895 mWakelock.setWorkSource(null);
1896
1897 // If there was an agent error, no timeout/completion handling will occur.
1898 // That means we need to deal with the next state ourselves.
1899 if (mStatus != BackupConstants.TRANSPORT_OK) {
1900 BackupState nextState = BackupState.RUNNING_QUEUE;
1901
1902 // An agent-level failure means we reenqueue this one agent for
1903 // a later retry, but otherwise proceed normally.
1904 if (mStatus == BackupConstants.AGENT_ERROR) {
1905 if (MORE_DEBUG) Slog.i(TAG, "Agent failure for " + request.packageName
1906 + " - restaging");
1907 dataChangedImpl(request.packageName);
1908 mStatus = BackupConstants.TRANSPORT_OK;
1909 if (mQueue.isEmpty()) nextState = BackupState.FINAL;
1910 } else if (mStatus != BackupConstants.TRANSPORT_OK) {
1911 // Transport-level failure means we reenqueue everything
1912 revertAndEndBackup();
1913 nextState = BackupState.FINAL;
1914 }
1915
1916 executeNextState(nextState);
Christopher Tate043dadc2009-06-02 16:11:00 -07001917 }
1918 }
1919 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001920
Christopher Tate8e294d42011-08-31 20:37:12 -07001921 void finalizeBackup() {
1922 // Either backup was successful, in which case we of course do not need
1923 // this pass's journal any more; or it failed, in which case we just
1924 // re-enqueued all of these packages in the current active journal.
1925 // Either way, we no longer need this pass's journal.
1926 if (mJournal != null && !mJournal.delete()) {
1927 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
1928 }
1929
1930 // If everything actually went through and this is the first time we've
1931 // done a backup, we can now record what the current backup dataset token
1932 // is.
1933 if ((mCurrentToken == 0) && (mStatus == BackupConstants.TRANSPORT_OK)) {
1934 try {
1935 mCurrentToken = mTransport.getCurrentRestoreSet();
1936 } catch (RemoteException e) {} // can't happen
1937 writeRestoreTokens();
1938 }
1939
1940 // Set up the next backup pass
1941 if (mStatus == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1942 backupNow();
1943 }
1944
1945 // Only once we're entirely finished do we release the wakelock
1946 Slog.i(TAG, "Backup pass finished.");
1947 mWakelock.release();
1948 }
1949
1950 // Invoke an agent's doBackup() and start a timeout message spinning on the main
1951 // handler in case it doesn't get back to us.
1952 int invokeAgentForBackup(String packageName, IBackupAgent agent,
Dan Egnor01445162009-09-21 17:04:05 -07001953 IBackupTransport transport) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001954 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001955
Christopher Tate8e294d42011-08-31 20:37:12 -07001956 mSavedStateName = new File(mStateDir, packageName);
1957 mBackupDataName = new File(mDataDir, packageName + ".data");
1958 mNewStateName = new File(mStateDir, packageName + ".new");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001959
Christopher Tate8e294d42011-08-31 20:37:12 -07001960 mSavedState = null;
1961 mBackupData = null;
1962 mNewState = null;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001963
Christopher Tate4a627c72011-04-01 14:43:32 -07001964 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001965 try {
1966 // Look up the package info & signatures. This is first so that if it
1967 // throws an exception, there's no file setup yet that would need to
1968 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001969 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001970 // The metadata 'package' is synthetic; construct one and make
1971 // sure our global state is pointed at it
1972 mCurrentPackage = new PackageInfo();
1973 mCurrentPackage.packageName = packageName;
Christopher Tateabce4e82009-06-18 18:35:32 -07001974 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001975
Christopher Tatec7b31e32009-06-10 15:49:30 -07001976 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001977 // the saved-state "file". This is by definition an incremental,
1978 // so we build a saved state file to pass.
Christopher Tate8e294d42011-08-31 20:37:12 -07001979 mSavedState = ParcelFileDescriptor.open(mSavedStateName,
Christopher Tate4a627c72011-04-01 14:43:32 -07001980 ParcelFileDescriptor.MODE_READ_ONLY |
1981 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001982
Christopher Tate8e294d42011-08-31 20:37:12 -07001983 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001984 ParcelFileDescriptor.MODE_READ_WRITE |
1985 ParcelFileDescriptor.MODE_CREATE |
1986 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001987
Christopher Tate8e294d42011-08-31 20:37:12 -07001988 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001989 ParcelFileDescriptor.MODE_READ_WRITE |
1990 ParcelFileDescriptor.MODE_CREATE |
1991 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001992
Christopher Tate44a27902010-01-27 17:15:49 -08001993 // Initiate the target's backup pass
Christopher Tate8e294d42011-08-31 20:37:12 -07001994 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, this);
1995 agent.doBackup(mSavedState, mBackupData, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001996 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07001997 Slog.e(TAG, "Error invoking for backup on " + packageName);
1998 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName,
1999 e.toString());
2000 agentErrorCleanup();
2001 return BackupConstants.AGENT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002002 }
2003
Christopher Tate8e294d42011-08-31 20:37:12 -07002004 // At this point the agent is off and running. The next thing to happen will
2005 // either be a callback from the agent, at which point we'll process its data
2006 // for transport, or a timeout. Either way the next phase will happen in
2007 // response to the TimeoutHandler interface callbacks.
2008 return BackupConstants.TRANSPORT_OK;
2009 }
2010
2011 @Override
2012 public void operationComplete() {
2013 // Okay, the agent successfully reported back to us. Spin the data off to the
2014 // transport and proceed with the next stage.
2015 if (MORE_DEBUG) Slog.v(TAG, "operationComplete(): sending data to transport for "
2016 + mCurrentPackage.packageName);
2017 mBackupHandler.removeMessages(MSG_TIMEOUT);
2018 clearAgentState();
2019
2020 ParcelFileDescriptor backupData = null;
2021 mStatus = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002022 try {
Christopher Tate8e294d42011-08-31 20:37:12 -07002023 int size = (int) mBackupDataName.length();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002024 if (size > 0) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002025 if (mStatus == BackupConstants.TRANSPORT_OK) {
2026 backupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnor01445162009-09-21 17:04:05 -07002027 ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate8e294d42011-08-31 20:37:12 -07002028 mStatus = mTransport.performBackup(mCurrentPackage, backupData);
Dan Egnor01445162009-09-21 17:04:05 -07002029 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002030
Dan Egnor83861e72009-09-17 16:17:55 -07002031 // TODO - We call finishBackup() for each application backed up, because
2032 // we need to know now whether it succeeded or failed. Instead, we should
2033 // hold off on finishBackup() until the end, which implies holding off on
2034 // renaming *all* the output state files (see below) until that happens.
2035
Christopher Tate8e294d42011-08-31 20:37:12 -07002036 if (mStatus == BackupConstants.TRANSPORT_OK) {
2037 mStatus = mTransport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07002038 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002039 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002040 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002041 }
2042
2043 // After successful transport, delete the now-stale data
2044 // and juggle the files so that next time we supply the agent
2045 // with the new state file it just created.
Christopher Tate8e294d42011-08-31 20:37:12 -07002046 if (mStatus == BackupConstants.TRANSPORT_OK) {
2047 mBackupDataName.delete();
2048 mNewStateName.renameTo(mSavedStateName);
2049 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE,
2050 mCurrentPackage.packageName, size);
2051 logBackupComplete(mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002052 } else {
Christopher Tate8e294d42011-08-31 20:37:12 -07002053 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2054 mCurrentPackage.packageName);
Dan Egnor01445162009-09-21 17:04:05 -07002055 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07002056 } catch (Exception e) {
Christopher Tate8e294d42011-08-31 20:37:12 -07002057 Slog.e(TAG, "Transport error backing up " + mCurrentPackage.packageName, e);
2058 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE,
2059 mCurrentPackage.packageName);
2060 mStatus = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002061 } finally {
2062 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07002063 }
Christopher Tated55e18a2009-09-21 10:12:59 -07002064
Christopher Tate8e294d42011-08-31 20:37:12 -07002065 // If we encountered an error here it's a transport-level failure. That
2066 // means we need to halt everything and reschedule everything for next time.
2067 final BackupState nextState;
2068 if (mStatus != BackupConstants.TRANSPORT_OK) {
2069 revertAndEndBackup();
2070 nextState = BackupState.FINAL;
2071 } else {
2072 // Success! Proceed with the next app if any, otherwise we're done.
2073 nextState = (mQueue.isEmpty()) ? BackupState.FINAL : BackupState.RUNNING_QUEUE;
2074 }
2075
2076 executeNextState(nextState);
2077 }
2078
2079 @Override
2080 public void handleTimeout() {
2081 // Whoops, the current agent timed out running doBackup(). Tidy up and restage
2082 // it for the next time we run a backup pass.
2083 // !!! TODO: keep track of failure counts per agent, and blacklist those which
2084 // fail repeatedly (i.e. have proved themselves to be buggy).
2085 Slog.e(TAG, "Timeout backing up " + mCurrentPackage.packageName);
2086 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, mCurrentPackage.packageName,
2087 "timeout");
2088 agentErrorCleanup();
2089 dataChangedImpl(mCurrentPackage.packageName);
2090 }
2091
2092 void revertAndEndBackup() {
2093 if (MORE_DEBUG) Slog.i(TAG, "Reverting backup queue - restaging everything");
2094 for (BackupRequest request : mOriginalQueue) {
2095 dataChangedImpl(request.packageName);
2096 }
2097 // We also want to reset the backup schedule based on whatever
2098 // the transport suggests by way of retry/backoff time.
2099 restartBackupAlarm();
2100 }
2101
2102 void agentErrorCleanup() {
2103 mBackupDataName.delete();
2104 mNewStateName.delete();
2105 clearAgentState();
2106
2107 executeNextState(mQueue.isEmpty() ? BackupState.FINAL : BackupState.RUNNING_QUEUE);
2108 }
2109
2110 // Cleanup common to both success and failure cases
2111 void clearAgentState() {
2112 try { if (mSavedState != null) mSavedState.close(); } catch (IOException e) {}
2113 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
2114 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
2115 mSavedState = mBackupData = mNewState = null;
2116 synchronized (mCurrentOpLock) {
2117 mCurrentOperations.clear();
2118 }
2119
2120 // If this was a pseudopackage there's no associated Activity Manager state
2121 if (mCurrentPackage.applicationInfo != null) {
2122 try { // unbind even on timeout, just in case
2123 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
2124 } catch (RemoteException e) {}
2125 }
2126 }
2127
2128 void restartBackupAlarm() {
2129 synchronized (mQueueLock) {
2130 try {
2131 startBackupAlarmsLocked(mTransport.requestBackupTime());
2132 } catch (RemoteException e) { /* cannot happen */ }
2133 }
2134 }
2135
2136 void executeNextState(BackupState nextState) {
2137 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
2138 + this + " nextState=" + nextState);
2139 mCurrentState = nextState;
2140 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
2141 mBackupHandler.sendMessage(msg);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002142 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002143 }
2144
Christopher Tatedf01dea2009-06-09 20:45:02 -07002145
Christopher Tate4a627c72011-04-01 14:43:32 -07002146 // ----- Full backup to a file/socket -----
2147
2148 class PerformFullBackupTask implements Runnable {
2149 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07002150 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07002151 IFullBackupRestoreObserver mObserver;
2152 boolean mIncludeApks;
2153 boolean mIncludeShared;
2154 boolean mAllApps;
2155 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002156 String mCurrentPassword;
2157 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07002158 AtomicBoolean mLatchObject;
2159 File mFilesDir;
2160 File mManifestFile;
2161
Christopher Tate7926a692011-07-11 11:31:57 -07002162 class FullBackupRunner implements Runnable {
2163 PackageInfo mPackage;
2164 IBackupAgent mAgent;
2165 ParcelFileDescriptor mPipe;
2166 int mToken;
2167 boolean mSendApk;
2168
2169 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
2170 int token, boolean sendApk) throws IOException {
2171 mPackage = pack;
2172 mAgent = agent;
2173 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
2174 mToken = token;
2175 mSendApk = sendApk;
2176 }
2177
2178 @Override
2179 public void run() {
2180 try {
2181 BackupDataOutput output = new BackupDataOutput(
2182 mPipe.getFileDescriptor());
2183
Christopher Tatec58efa62011-08-01 19:20:14 -07002184 if (MORE_DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
Christopher Tate7926a692011-07-11 11:31:57 -07002185 writeAppManifest(mPackage, mManifestFile, mSendApk);
2186 FullBackup.backupToTar(mPackage.packageName, null, null,
2187 mFilesDir.getAbsolutePath(),
2188 mManifestFile.getAbsolutePath(),
2189 output);
2190
2191 if (mSendApk) {
2192 writeApkToBackup(mPackage, output);
2193 }
2194
Christopher Tatec58efa62011-08-01 19:20:14 -07002195 if (DEBUG) Slog.d(TAG, "Calling doFullBackup() on " + mPackage.packageName);
Christopher Tate8e294d42011-08-31 20:37:12 -07002196 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate7926a692011-07-11 11:31:57 -07002197 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
2198 } catch (IOException e) {
2199 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
2200 } catch (RemoteException e) {
2201 Slog.e(TAG, "Remote agent vanished during full backup of "
2202 + mPackage.packageName);
2203 } finally {
2204 try {
2205 mPipe.close();
2206 } catch (IOException e) {}
2207 }
2208 }
2209 }
2210
Christopher Tate4a627c72011-04-01 14:43:32 -07002211 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07002212 boolean includeApks, boolean includeShared, String curPassword,
2213 String encryptPassword, boolean doAllApps, String[] packages,
2214 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002215 mOutputFile = fd;
2216 mObserver = observer;
2217 mIncludeApks = includeApks;
2218 mIncludeShared = includeShared;
2219 mAllApps = doAllApps;
2220 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07002221 mCurrentPassword = curPassword;
2222 // when backing up, if there is a current backup password, we require that
2223 // the user use a nonempty encryption password as well. if one is supplied
2224 // in the UI we use that, but if the UI was left empty we fall back to the
2225 // current backup password (which was supplied by the user as well).
2226 if (encryptPassword == null || "".equals(encryptPassword)) {
2227 mEncryptPassword = curPassword;
2228 } else {
2229 mEncryptPassword = encryptPassword;
2230 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002231 mLatchObject = latch;
2232
2233 mFilesDir = new File("/data/system");
2234 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
2235 }
2236
2237 @Override
2238 public void run() {
2239 final List<PackageInfo> packagesToBackup;
2240
Christopher Tateb0628bf2011-06-02 15:08:13 -07002241 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07002242 sendStartBackup();
2243
2244 // doAllApps supersedes the package set if any
2245 if (mAllApps) {
2246 packagesToBackup = mPackageManager.getInstalledPackages(
2247 PackageManager.GET_SIGNATURES);
2248 } else {
2249 packagesToBackup = new ArrayList<PackageInfo>();
2250 for (String pkgName : mPackages) {
2251 try {
2252 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2253 PackageManager.GET_SIGNATURES));
2254 } catch (NameNotFoundException e) {
2255 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2256 }
2257 }
2258 }
2259
Christopher Tatea858cb02011-06-03 12:27:51 -07002260 // Cull any packages that have indicated that backups are not permitted.
2261 for (int i = 0; i < packagesToBackup.size(); ) {
2262 PackageInfo info = packagesToBackup.get(i);
2263 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2264 packagesToBackup.remove(i);
2265 } else {
2266 i++;
2267 }
2268 }
2269
Christopher Tate7926a692011-07-11 11:31:57 -07002270 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002271 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002272
Christopher Tate4a627c72011-04-01 14:43:32 -07002273 PackageInfo pkg = null;
2274 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002275 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002276 boolean compressing = COMPRESS_FULL_BACKUPS;
2277 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002278
Christopher Tateeef4ae42011-08-05 13:15:53 -07002279 // Verify that the given password matches the currently-active
2280 // backup password, if any
2281 if (hasBackupPassword()) {
2282 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2283 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2284 return;
2285 }
2286 }
2287
Christopher Tate7bdb0962011-07-13 19:30:21 -07002288 // Write the global file header. All strings are UTF-8 encoded; lines end
2289 // with a '\n' byte. Actual backup data begins immediately following the
2290 // final '\n'.
2291 //
2292 // line 1: "ANDROID BACKUP"
2293 // line 2: backup file format version, currently "1"
2294 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002295 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2296 //
2297 // When line 4 is not "none", then additional header data follows:
2298 //
2299 // line 5: user password salt [hex]
2300 // line 6: master key checksum salt [hex]
2301 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2302 // line 8: IV of the user key [hex]
2303 // line 9: master key blob [hex]
2304 // IV of the master key, master key itself, master key checksum hash
2305 //
2306 // The master key checksum is the master key plus its checksum salt, run through
2307 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2308 // correct password for decrypting the archive: the master key decrypted from
2309 // the archive using the user-supplied password is also run through PBKDF2 in
2310 // this way, and if the result does not match the checksum as stored in the
2311 // archive, then we know that the user-supplied password does not match the
2312 // archive's.
2313 StringBuilder headerbuf = new StringBuilder(1024);
2314
Christopher Tate7bdb0962011-07-13 19:30:21 -07002315 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002316 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2317 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002318
2319 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002320 // Set up the encryption stage if appropriate, and emit the correct header
2321 if (encrypting) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002322 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2323 } else {
2324 headerbuf.append("none\n");
2325 }
2326
Christopher Tate7bdb0962011-07-13 19:30:21 -07002327 byte[] header = headerbuf.toString().getBytes("UTF-8");
2328 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002329
2330 // Set up the compression stage feeding into the encryption stage (if any)
2331 if (compressing) {
2332 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2333 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2334 }
2335
2336 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002337 } catch (Exception e) {
2338 // Should never happen!
2339 Slog.e(TAG, "Unable to emit archive header", e);
2340 return;
2341 }
2342
Christopher Tateb0628bf2011-06-02 15:08:13 -07002343 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002344 int N = packagesToBackup.size();
2345 for (int i = 0; i < N; i++) {
2346 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002347 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002348 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002349
Christopher Tate6853fcf2011-08-10 17:52:21 -07002350 // Shared storage if requested
Christopher Tateb0628bf2011-06-02 15:08:13 -07002351 if (mIncludeShared) {
2352 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002353 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07002354
2355 // Done!
2356 finalizeBackup(out);
Christopher Tate4a627c72011-04-01 14:43:32 -07002357 } catch (RemoteException e) {
2358 Slog.e(TAG, "App died during full backup");
2359 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002360 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002361 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002362 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002363 mOutputFile.close();
2364 } catch (IOException e) {
2365 /* nothing we can do about this */
2366 }
2367 synchronized (mCurrentOpLock) {
2368 mCurrentOperations.clear();
2369 }
2370 synchronized (mLatchObject) {
2371 mLatchObject.set(true);
2372 mLatchObject.notifyAll();
2373 }
2374 sendEndBackup();
2375 mWakelock.release();
2376 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2377 }
2378 }
2379
Christopher Tate2efd2db2011-07-19 16:32:49 -07002380 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2381 OutputStream ofstream) throws Exception {
2382 // User key will be used to encrypt the master key.
2383 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002384 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002385 PBKDF2_HASH_ROUNDS);
2386
2387 // the master key is random for each backup
2388 byte[] masterPw = new byte[256 / 8];
2389 mRng.nextBytes(masterPw);
2390 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2391
2392 // primary encryption of the datastream with the random key
2393 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2394 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2395 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2396 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2397
2398 // line 4: name of encryption algorithm
2399 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2400 headerbuf.append('\n');
2401 // line 5: user password salt [hex]
2402 headerbuf.append(byteArrayToHex(newUserSalt));
2403 headerbuf.append('\n');
2404 // line 6: master key checksum salt [hex]
2405 headerbuf.append(byteArrayToHex(checksumSalt));
2406 headerbuf.append('\n');
2407 // line 7: number of PBKDF2 rounds used [decimal]
2408 headerbuf.append(PBKDF2_HASH_ROUNDS);
2409 headerbuf.append('\n');
2410
2411 // line 8: IV of the user key [hex]
2412 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2413 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2414
2415 byte[] IV = mkC.getIV();
2416 headerbuf.append(byteArrayToHex(IV));
2417 headerbuf.append('\n');
2418
2419 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2420 // [byte] IV length = Niv
2421 // [array of Niv bytes] IV itself
2422 // [byte] master key length = Nmk
2423 // [array of Nmk bytes] master key itself
2424 // [byte] MK checksum hash length = Nck
2425 // [array of Nck bytes] master key checksum hash
2426 //
2427 // The checksum is the (master key + checksum salt), run through the
2428 // stated number of PBKDF2 rounds
2429 IV = c.getIV();
2430 byte[] mk = masterKeySpec.getEncoded();
2431 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2432 checksumSalt, PBKDF2_HASH_ROUNDS);
2433
2434 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2435 + checksum.length + 3);
2436 DataOutputStream mkOut = new DataOutputStream(blob);
2437 mkOut.writeByte(IV.length);
2438 mkOut.write(IV);
2439 mkOut.writeByte(mk.length);
2440 mkOut.write(mk);
2441 mkOut.writeByte(checksum.length);
2442 mkOut.write(checksum);
2443 mkOut.flush();
2444 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2445 headerbuf.append(byteArrayToHex(encryptedMk));
2446 headerbuf.append('\n');
2447
2448 return finalOutput;
2449 }
2450
2451 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002452 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002453 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2454
2455 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2456 IApplicationThread.BACKUP_MODE_FULL);
2457 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002458 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002459 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002460 pipes = ParcelFileDescriptor.createPipe();
2461
Christopher Tateb0628bf2011-06-02 15:08:13 -07002462 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002463 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002464 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2465 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2466 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2467
2468 sendOnBackupPackage(pkg.packageName);
2469
Christopher Tate7926a692011-07-11 11:31:57 -07002470 final int token = generateToken();
2471 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2472 token, sendApk);
2473 pipes[1].close(); // the runner has dup'd it
2474 pipes[1] = null;
2475 Thread t = new Thread(runner);
2476 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002477
Christopher Tate7926a692011-07-11 11:31:57 -07002478 // Now pull data from the app and stuff it into the compressor
2479 try {
2480 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2481 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002482
Christopher Tate7926a692011-07-11 11:31:57 -07002483 byte[] buffer = new byte[16 * 1024];
2484 int chunkTotal;
2485 while ((chunkTotal = in.readInt()) > 0) {
2486 while (chunkTotal > 0) {
2487 int toRead = (chunkTotal > buffer.length)
2488 ? buffer.length : chunkTotal;
2489 int nRead = in.read(buffer, 0, toRead);
2490 out.write(buffer, 0, nRead);
2491 chunkTotal -= nRead;
2492 }
2493 }
2494 } catch (IOException e) {
2495 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002496 }
2497
Christopher Tateb0628bf2011-06-02 15:08:13 -07002498 if (!waitUntilOperationComplete(token)) {
2499 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2500 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002501 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002502 }
Christopher Tate7926a692011-07-11 11:31:57 -07002503
Christopher Tateb0628bf2011-06-02 15:08:13 -07002504 } catch (IOException e) {
2505 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002506 } finally {
2507 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002508 // flush after every package
2509 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002510 if (pipes != null) {
2511 if (pipes[0] != null) pipes[0].close();
2512 if (pipes[1] != null) pipes[1].close();
2513 }
Christopher Tate7926a692011-07-11 11:31:57 -07002514 } catch (IOException e) {
2515 Slog.w(TAG, "Error bringing down backup stack");
2516 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002517 }
2518 } else {
2519 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2520 }
2521 tearDown(pkg);
2522 }
2523
Christopher Tate79ec80d2011-06-24 14:58:49 -07002524 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2525 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2526 final String appSourceDir = pkg.applicationInfo.sourceDir;
2527 final String apkDir = new File(appSourceDir).getParent();
2528 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2529 apkDir, appSourceDir, output);
2530
2531 // Save associated .obb content if it exists and we did save the apk
2532 // check for .obb and save those too
2533 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2534 if (obbDir != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002535 if (MORE_DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
Christopher Tate79ec80d2011-06-24 14:58:49 -07002536 File[] obbFiles = obbDir.listFiles();
2537 if (obbFiles != null) {
2538 final String obbDirName = obbDir.getAbsolutePath();
2539 for (File obb : obbFiles) {
2540 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2541 obbDirName, obb.getAbsolutePath(), output);
2542 }
2543 }
2544 }
2545 }
2546
Christopher Tateb0628bf2011-06-02 15:08:13 -07002547 private void backupSharedStorage() throws RemoteException {
2548 PackageInfo pkg = null;
2549 try {
2550 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2551 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2552 IApplicationThread.BACKUP_MODE_FULL);
2553 if (agent != null) {
2554 sendOnBackupPackage("Shared storage");
2555
2556 final int token = generateToken();
Christopher Tate8e294d42011-08-31 20:37:12 -07002557 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL, null);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002558 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002559 if (!waitUntilOperationComplete(token)) {
2560 Slog.e(TAG, "Full backup failed on shared storage");
2561 } else {
2562 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2563 }
2564 } else {
2565 Slog.e(TAG, "Could not bind to shared storage backup agent");
2566 }
2567 } catch (NameNotFoundException e) {
2568 Slog.e(TAG, "Shared storage backup package not found");
2569 } finally {
2570 tearDown(pkg);
2571 }
2572 }
2573
Christopher Tate6853fcf2011-08-10 17:52:21 -07002574 private void finalizeBackup(OutputStream out) {
2575 try {
2576 // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
2577 byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
2578 out.write(eof);
2579 } catch (IOException e) {
2580 Slog.w(TAG, "Error attempting to finalize backup stream");
2581 }
2582 }
2583
Christopher Tate4a627c72011-04-01 14:43:32 -07002584 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2585 throws IOException {
2586 // Manifest format. All data are strings ending in LF:
2587 // BACKUP_MANIFEST_VERSION, currently 1
2588 //
2589 // Version 1:
2590 // package name
2591 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002592 // platform versionCode
2593 // getInstallerPackageName() for this package (maybe empty)
2594 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002595 // number of signatures == N
2596 // N*: signature byte array in ascii format per Signature.toCharsString()
2597 StringBuilder builder = new StringBuilder(4096);
2598 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2599
2600 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2601 printer.println(pkg.packageName);
2602 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002603 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2604
2605 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2606 printer.println((installerName != null) ? installerName : "");
2607
Christopher Tate4a627c72011-04-01 14:43:32 -07002608 printer.println(withApk ? "1" : "0");
2609 if (pkg.signatures == null) {
2610 printer.println("0");
2611 } else {
2612 printer.println(Integer.toString(pkg.signatures.length));
2613 for (Signature sig : pkg.signatures) {
2614 printer.println(sig.toCharsString());
2615 }
2616 }
2617
2618 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002619 outstream.write(builder.toString().getBytes());
2620 outstream.close();
2621 }
2622
2623 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002624 if (pkg != null) {
2625 final ApplicationInfo app = pkg.applicationInfo;
2626 if (app != null) {
2627 try {
2628 // unbind and tidy up even on timeout or failure, just in case
2629 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002630
Christopher Tateb0628bf2011-06-02 15:08:13 -07002631 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002632 if (app.uid != Process.SYSTEM_UID
2633 && app.uid != Process.PHONE_UID) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002634 if (MORE_DEBUG) Slog.d(TAG, "Backup complete, killing host process");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002635 mActivityManager.killApplicationProcess(app.processName, app.uid);
2636 } else {
Christopher Tatec58efa62011-08-01 19:20:14 -07002637 if (MORE_DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002638 }
2639 } catch (RemoteException e) {
2640 Slog.d(TAG, "Lost app trying to shut down");
2641 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002642 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002643 }
2644 }
2645
2646 // wrappers for observer use
2647 void sendStartBackup() {
2648 if (mObserver != null) {
2649 try {
2650 mObserver.onStartBackup();
2651 } catch (RemoteException e) {
2652 Slog.w(TAG, "full backup observer went away: startBackup");
2653 mObserver = null;
2654 }
2655 }
2656 }
2657
2658 void sendOnBackupPackage(String name) {
2659 if (mObserver != null) {
2660 try {
2661 // TODO: use a more user-friendly name string
2662 mObserver.onBackupPackage(name);
2663 } catch (RemoteException e) {
2664 Slog.w(TAG, "full backup observer went away: backupPackage");
2665 mObserver = null;
2666 }
2667 }
2668 }
2669
2670 void sendEndBackup() {
2671 if (mObserver != null) {
2672 try {
2673 mObserver.onEndBackup();
2674 } catch (RemoteException e) {
2675 Slog.w(TAG, "full backup observer went away: endBackup");
2676 mObserver = null;
2677 }
2678 }
2679 }
2680 }
2681
2682
Christopher Tate75a99702011-05-18 16:28:19 -07002683 // ----- Full restore from a file/socket -----
2684
2685 // Description of a file in the restore datastream
2686 static class FileMetadata {
2687 String packageName; // name of the owning app
2688 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002689 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002690 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2691 String path; // subpath within the semantic domain
2692 long mode; // e.g. 0666 (actually int)
2693 long mtime; // last mod time, UTC time_t (actually int)
2694 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002695
2696 @Override
2697 public String toString() {
2698 StringBuilder sb = new StringBuilder(128);
2699 sb.append("FileMetadata{");
2700 sb.append(packageName); sb.append(',');
2701 sb.append(type); sb.append(',');
2702 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2703 sb.append(size);
2704 sb.append('}');
2705 return sb.toString();
2706 }
Christopher Tate75a99702011-05-18 16:28:19 -07002707 }
2708
2709 enum RestorePolicy {
2710 IGNORE,
2711 ACCEPT,
2712 ACCEPT_IF_APK
2713 }
2714
2715 class PerformFullRestoreTask implements Runnable {
2716 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002717 String mCurrentPassword;
2718 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002719 IFullBackupRestoreObserver mObserver;
2720 AtomicBoolean mLatchObject;
2721 IBackupAgent mAgent;
2722 String mAgentPackage;
2723 ApplicationInfo mTargetApp;
2724 ParcelFileDescriptor[] mPipes = null;
2725
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002726 long mBytes;
2727
Christopher Tate75a99702011-05-18 16:28:19 -07002728 // possible handling states for a given package in the restore dataset
2729 final HashMap<String, RestorePolicy> mPackagePolicies
2730 = new HashMap<String, RestorePolicy>();
2731
2732 // installer package names for each encountered app, derived from the manifests
2733 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2734
2735 // Signatures for a given package found in its manifest file
2736 final HashMap<String, Signature[]> mManifestSignatures
2737 = new HashMap<String, Signature[]>();
2738
2739 // Packages we've already wiped data on when restoring their first file
2740 final HashSet<String> mClearedPackages = new HashSet<String>();
2741
Christopher Tate728a1c42011-07-28 18:03:03 -07002742 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002743 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002744 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002745 mCurrentPassword = curPassword;
2746 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002747 mObserver = observer;
2748 mLatchObject = latch;
2749 mAgent = null;
2750 mAgentPackage = null;
2751 mTargetApp = null;
2752
2753 // Which packages we've already wiped data on. We prepopulate this
2754 // with a whitelist of packages known to be unclearable.
2755 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002756 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002757
Christopher Tate75a99702011-05-18 16:28:19 -07002758 }
2759
2760 class RestoreFileRunnable implements Runnable {
2761 IBackupAgent mAgent;
2762 FileMetadata mInfo;
2763 ParcelFileDescriptor mSocket;
2764 int mToken;
2765
2766 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2767 ParcelFileDescriptor socket, int token) throws IOException {
2768 mAgent = agent;
2769 mInfo = info;
2770 mToken = token;
2771
2772 // This class is used strictly for process-local binder invocations. The
2773 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2774 // do not automatically get a 'dup'ed descriptor that we can can continue
2775 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2776 // before proceeding to do the restore.
2777 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2778 }
2779
2780 @Override
2781 public void run() {
2782 try {
2783 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2784 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2785 mToken, mBackupManagerBinder);
2786 } catch (RemoteException e) {
2787 // never happens; this is used strictly for local binder calls
2788 }
2789 }
2790 }
2791
2792 @Override
2793 public void run() {
2794 Slog.i(TAG, "--- Performing full-dataset restore ---");
2795 sendStartRestore();
2796
Christopher Tateb0628bf2011-06-02 15:08:13 -07002797 // Are we able to restore shared-storage data?
2798 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2799 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2800 }
2801
Christopher Tate2efd2db2011-07-19 16:32:49 -07002802 FileInputStream rawInStream = null;
2803 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002804 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002805 if (hasBackupPassword()) {
2806 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2807 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2808 return;
2809 }
2810 }
2811
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002812 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002813 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002814 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2815 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002816
2817 // First, parse out the unencrypted/uncompressed header
2818 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002819 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002820 final InputStream in;
2821
2822 boolean okay = false;
2823 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2824 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002825 rawDataIn.readFully(streamHeader);
2826 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2827 if (Arrays.equals(magicBytes, streamHeader)) {
2828 // okay, header looks good. now parse out the rest of the fields.
2829 String s = readHeaderLine(rawInStream);
2830 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2831 // okay, it's a version we recognize
2832 s = readHeaderLine(rawInStream);
2833 compressed = (Integer.parseInt(s) != 0);
2834 s = readHeaderLine(rawInStream);
2835 if (s.equals("none")) {
2836 // no more header to parse; we're good to go
2837 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002838 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002839 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2840 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002841 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002842 }
2843 } else Slog.w(TAG, "Archive is encrypted but no password given");
2844 } else Slog.w(TAG, "Wrong header version: " + s);
2845 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002846
2847 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002848 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002849 return;
2850 }
2851
2852 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002853 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002854
2855 boolean didRestore;
2856 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002857 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002858 } while (didRestore);
2859
Christopher Tatec58efa62011-08-01 19:20:14 -07002860 if (MORE_DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002861 } catch (IOException e) {
2862 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002863 } finally {
2864 tearDownPipes();
2865 tearDownAgent(mTargetApp);
2866
2867 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002868 if (rawDataIn != null) rawDataIn.close();
2869 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002870 mInputFile.close();
2871 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002872 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002873 /* nothing we can do about this */
2874 }
2875 synchronized (mCurrentOpLock) {
2876 mCurrentOperations.clear();
2877 }
2878 synchronized (mLatchObject) {
2879 mLatchObject.set(true);
2880 mLatchObject.notifyAll();
2881 }
2882 sendEndRestore();
2883 mWakelock.release();
Christopher Tatec58efa62011-08-01 19:20:14 -07002884 Slog.d(TAG, "Full restore pass complete.");
Christopher Tate75a99702011-05-18 16:28:19 -07002885 }
2886 }
2887
Christopher Tate7bdb0962011-07-13 19:30:21 -07002888 String readHeaderLine(InputStream in) throws IOException {
2889 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002890 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002891 while ((c = in.read()) >= 0) {
2892 if (c == '\n') break; // consume and discard the newlines
2893 buffer.append((char)c);
2894 }
2895 return buffer.toString();
2896 }
2897
Christopher Tate2efd2db2011-07-19 16:32:49 -07002898 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2899 InputStream result = null;
2900 try {
2901 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2902
2903 String userSaltHex = readHeaderLine(rawInStream); // 5
2904 byte[] userSalt = hexToByteArray(userSaltHex);
2905
2906 String ckSaltHex = readHeaderLine(rawInStream); // 6
2907 byte[] ckSalt = hexToByteArray(ckSaltHex);
2908
2909 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2910 String userIvHex = readHeaderLine(rawInStream); // 8
2911
2912 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2913
2914 // decrypt the master key blob
2915 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002916 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002917 rounds);
2918 byte[] IV = hexToByteArray(userIvHex);
2919 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2920 c.init(Cipher.DECRYPT_MODE,
2921 new SecretKeySpec(userKey.getEncoded(), "AES"),
2922 ivSpec);
2923 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2924 byte[] mkBlob = c.doFinal(mkCipher);
2925
2926 // first, the master key IV
2927 int offset = 0;
2928 int len = mkBlob[offset++];
2929 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2930 offset += len;
2931 // then the master key itself
2932 len = mkBlob[offset++];
2933 byte[] mk = Arrays.copyOfRange(mkBlob,
2934 offset, offset + len);
2935 offset += len;
2936 // and finally the master key checksum hash
2937 len = mkBlob[offset++];
2938 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2939 offset, offset + len);
2940
2941 // now validate the decrypted master key against the checksum
2942 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2943 if (Arrays.equals(calculatedCk, mkChecksum)) {
2944 ivSpec = new IvParameterSpec(IV);
2945 c.init(Cipher.DECRYPT_MODE,
2946 new SecretKeySpec(mk, "AES"),
2947 ivSpec);
2948 // Only if all of the above worked properly will 'result' be assigned
2949 result = new CipherInputStream(rawInStream, c);
2950 } else Slog.w(TAG, "Incorrect password");
2951 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2952 } catch (InvalidAlgorithmParameterException e) {
2953 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2954 } catch (BadPaddingException e) {
2955 // This case frequently occurs when the wrong password is used to decrypt
2956 // the master key. Use the identical "incorrect password" log text as is
2957 // used in the checksum failure log in order to avoid providing additional
2958 // information to an attacker.
2959 Slog.w(TAG, "Incorrect password");
2960 } catch (IllegalBlockSizeException e) {
2961 Slog.w(TAG, "Invalid block size in master key");
2962 } catch (NoSuchAlgorithmException e) {
2963 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2964 } catch (NoSuchPaddingException e) {
2965 Slog.e(TAG, "Needed padding mechanism unavailable!");
2966 } catch (InvalidKeyException e) {
2967 Slog.w(TAG, "Illegal password; aborting");
2968 } catch (NumberFormatException e) {
2969 Slog.w(TAG, "Can't parse restore data header");
2970 } catch (IOException e) {
2971 Slog.w(TAG, "Can't read input header");
2972 }
2973
2974 return result;
2975 }
2976
Christopher Tate75a99702011-05-18 16:28:19 -07002977 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2978 FileMetadata info;
2979 try {
2980 info = readTarHeaders(instream);
2981 if (info != null) {
Christopher Tatec58efa62011-08-01 19:20:14 -07002982 if (MORE_DEBUG) {
Christopher Tate75a99702011-05-18 16:28:19 -07002983 dumpFileMetadata(info);
2984 }
2985
2986 final String pkg = info.packageName;
2987 if (!pkg.equals(mAgentPackage)) {
2988 // okay, change in package; set up our various
2989 // bookkeeping if we haven't seen it yet
2990 if (!mPackagePolicies.containsKey(pkg)) {
2991 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2992 }
2993
2994 // Clean up the previous agent relationship if necessary,
2995 // and let the observer know we're considering a new app.
2996 if (mAgent != null) {
2997 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2998 tearDownPipes();
2999 tearDownAgent(mTargetApp);
3000 mTargetApp = null;
3001 mAgentPackage = null;
3002 }
3003 }
3004
3005 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3006 mPackagePolicies.put(pkg, readAppManifest(info, instream));
3007 mPackageInstallers.put(pkg, info.installerPackageName);
3008 // We've read only the manifest content itself at this point,
3009 // so consume the footer before looping around to the next
3010 // input file
3011 skipTarPadding(info.size, instream);
3012 sendOnRestorePackage(pkg);
3013 } else {
3014 // Non-manifest, so it's actual file data. Is this a package
3015 // we're ignoring?
3016 boolean okay = true;
3017 RestorePolicy policy = mPackagePolicies.get(pkg);
3018 switch (policy) {
3019 case IGNORE:
3020 okay = false;
3021 break;
3022
3023 case ACCEPT_IF_APK:
3024 // If we're in accept-if-apk state, then the first file we
3025 // see MUST be the apk.
3026 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3027 if (DEBUG) Slog.d(TAG, "APK file; installing");
3028 // Try to install the app.
3029 String installerName = mPackageInstallers.get(pkg);
3030 okay = installApk(info, installerName, instream);
3031 // good to go; promote to ACCEPT
3032 mPackagePolicies.put(pkg, (okay)
3033 ? RestorePolicy.ACCEPT
3034 : RestorePolicy.IGNORE);
3035 // At this point we've consumed this file entry
3036 // ourselves, so just strip the tar footer and
3037 // go on to the next file in the input stream
3038 skipTarPadding(info.size, instream);
3039 return true;
3040 } else {
3041 // File data before (or without) the apk. We can't
3042 // handle it coherently in this case so ignore it.
3043 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3044 okay = false;
3045 }
3046 break;
3047
3048 case ACCEPT:
3049 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
3050 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
3051 // we can take the data without the apk, so we
3052 // *want* to do so. skip the apk by declaring this
3053 // one file not-okay without changing the restore
3054 // policy for the package.
3055 okay = false;
3056 }
3057 break;
3058
3059 default:
3060 // Something has gone dreadfully wrong when determining
3061 // the restore policy from the manifest. Ignore the
3062 // rest of this package's data.
3063 Slog.e(TAG, "Invalid policy from manifest");
3064 okay = false;
3065 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3066 break;
3067 }
3068
3069 // If the policy is satisfied, go ahead and set up to pipe the
3070 // data to the agent.
3071 if (DEBUG && okay && mAgent != null) {
3072 Slog.i(TAG, "Reusing existing agent instance");
3073 }
3074 if (okay && mAgent == null) {
3075 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
3076
3077 try {
3078 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
3079
3080 // If we haven't sent any data to this app yet, we probably
3081 // need to clear it first. Check that.
3082 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003083 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07003084 // responsible for coherently managing a full
3085 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07003086 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07003087 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
3088 clearApplicationDataSynchronous(pkg);
3089 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07003090 if (DEBUG) Slog.d(TAG, "backup agent ("
3091 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07003092 }
3093 mClearedPackages.add(pkg);
3094 } else {
3095 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
3096 }
3097
3098 // All set; now set up the IPC and launch the agent
3099 setUpPipes();
3100 mAgent = bindToAgentSynchronous(mTargetApp,
3101 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
3102 mAgentPackage = pkg;
3103 } catch (IOException e) {
3104 // fall through to error handling
3105 } catch (NameNotFoundException e) {
3106 // fall through to error handling
3107 }
3108
3109 if (mAgent == null) {
3110 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
3111 okay = false;
3112 tearDownPipes();
3113 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3114 }
3115 }
3116
3117 // Sanity check: make sure we never give data to the wrong app. This
3118 // should never happen but a little paranoia here won't go amiss.
3119 if (okay && !pkg.equals(mAgentPackage)) {
3120 Slog.e(TAG, "Restoring data for " + pkg
3121 + " but agent is for " + mAgentPackage);
3122 okay = false;
3123 }
3124
3125 // At this point we have an agent ready to handle the full
3126 // restore data as well as a pipe for sending data to
3127 // that agent. Tell the agent to start reading from the
3128 // pipe.
3129 if (okay) {
3130 boolean agentSuccess = true;
3131 long toCopy = info.size;
3132 final int token = generateToken();
3133 try {
3134 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
3135 + info.path);
Christopher Tate8e294d42011-08-31 20:37:12 -07003136 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, null);
Christopher Tate75a99702011-05-18 16:28:19 -07003137 // fire up the app's agent listening on the socket. If
3138 // the agent is running in the system process we can't
3139 // just invoke it asynchronously, so we provide a thread
3140 // for it here.
3141 if (mTargetApp.processName.equals("system")) {
3142 Slog.d(TAG, "system process agent - spinning a thread");
3143 RestoreFileRunnable runner = new RestoreFileRunnable(
3144 mAgent, info, mPipes[0], token);
3145 new Thread(runner).start();
3146 } else {
3147 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
3148 info.domain, info.path, info.mode, info.mtime,
3149 token, mBackupManagerBinder);
3150 }
3151 } catch (IOException e) {
3152 // couldn't dup the socket for a process-local restore
3153 Slog.d(TAG, "Couldn't establish restore");
3154 agentSuccess = false;
3155 okay = false;
3156 } catch (RemoteException e) {
3157 // whoops, remote agent went away. We'll eat the content
3158 // ourselves, then, and not copy it over.
3159 Slog.e(TAG, "Agent crashed during full restore");
3160 agentSuccess = false;
3161 okay = false;
3162 }
3163
3164 // Copy over the data if the agent is still good
3165 if (okay) {
3166 boolean pipeOkay = true;
3167 FileOutputStream pipe = new FileOutputStream(
3168 mPipes[1].getFileDescriptor());
Christopher Tate75a99702011-05-18 16:28:19 -07003169 while (toCopy > 0) {
3170 int toRead = (toCopy > buffer.length)
3171 ? buffer.length : (int)toCopy;
3172 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003173 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003174 if (nRead <= 0) break;
3175 toCopy -= nRead;
3176
3177 // send it to the output pipe as long as things
3178 // are still good
3179 if (pipeOkay) {
3180 try {
3181 pipe.write(buffer, 0, nRead);
3182 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003183 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003184 pipeOkay = false;
3185 }
3186 }
3187 }
3188
3189 // done sending that file! Now we just need to consume
3190 // the delta from info.size to the end of block.
3191 skipTarPadding(info.size, instream);
3192
3193 // and now that we've sent it all, wait for the remote
3194 // side to acknowledge receipt
3195 agentSuccess = waitUntilOperationComplete(token);
3196 }
3197
3198 // okay, if the remote end failed at any point, deal with
3199 // it by ignoring the rest of the restore on it
3200 if (!agentSuccess) {
3201 mBackupHandler.removeMessages(MSG_TIMEOUT);
3202 tearDownPipes();
3203 tearDownAgent(mTargetApp);
3204 mAgent = null;
3205 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
3206 }
3207 }
3208
3209 // Problems setting up the agent communication, or an already-
3210 // ignored package: skip to the next tar stream entry by
3211 // reading and discarding this file.
3212 if (!okay) {
3213 if (DEBUG) Slog.d(TAG, "[discarding file content]");
3214 long bytesToConsume = (info.size + 511) & ~511;
3215 while (bytesToConsume > 0) {
3216 int toRead = (bytesToConsume > buffer.length)
3217 ? buffer.length : (int)bytesToConsume;
3218 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003219 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003220 if (nRead <= 0) break;
3221 bytesToConsume -= nRead;
3222 }
3223 }
3224 }
3225 }
3226 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003227 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003228 // treat as EOF
3229 info = null;
3230 }
3231
3232 return (info != null);
3233 }
3234
3235 void setUpPipes() throws IOException {
3236 mPipes = ParcelFileDescriptor.createPipe();
3237 }
3238
3239 void tearDownPipes() {
3240 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003241 try {
3242 mPipes[0].close();
3243 mPipes[0] = null;
3244 mPipes[1].close();
3245 mPipes[1] = null;
3246 } catch (IOException e) {
3247 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07003248 }
3249 mPipes = null;
3250 }
3251 }
3252
3253 void tearDownAgent(ApplicationInfo app) {
3254 if (mAgent != null) {
3255 try {
3256 // unbind and tidy up even on timeout or failure, just in case
3257 mActivityManager.unbindBackupAgent(app);
3258
3259 // The agent was running with a stub Application object, so shut it down.
3260 // !!! We hardcode the confirmation UI's package name here rather than use a
3261 // manifest flag! TODO something less direct.
3262 if (app.uid != Process.SYSTEM_UID
3263 && !app.packageName.equals("com.android.backupconfirm")) {
3264 if (DEBUG) Slog.d(TAG, "Killing host process");
3265 mActivityManager.killApplicationProcess(app.processName, app.uid);
3266 } else {
3267 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3268 }
3269 } catch (RemoteException e) {
3270 Slog.d(TAG, "Lost app trying to shut down");
3271 }
3272 mAgent = null;
3273 }
3274 }
3275
3276 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3277 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003278 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003279 int mResult;
3280
3281 public void reset() {
3282 synchronized (mDone) {
3283 mDone.set(false);
3284 }
3285 }
3286
3287 public void waitForCompletion() {
3288 synchronized (mDone) {
3289 while (mDone.get() == false) {
3290 try {
3291 mDone.wait();
3292 } catch (InterruptedException e) { }
3293 }
3294 }
3295 }
3296
3297 int getResult() {
3298 return mResult;
3299 }
3300
3301 @Override
3302 public void packageInstalled(String packageName, int returnCode)
3303 throws RemoteException {
3304 synchronized (mDone) {
3305 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003306 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003307 mDone.set(true);
3308 mDone.notifyAll();
3309 }
3310 }
3311 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003312
3313 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3314 final AtomicBoolean mDone = new AtomicBoolean();
3315 int mResult;
3316
3317 public void reset() {
3318 synchronized (mDone) {
3319 mDone.set(false);
3320 }
3321 }
3322
3323 public void waitForCompletion() {
3324 synchronized (mDone) {
3325 while (mDone.get() == false) {
3326 try {
3327 mDone.wait();
3328 } catch (InterruptedException e) { }
3329 }
3330 }
3331 }
3332
3333 @Override
3334 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3335 synchronized (mDone) {
3336 mResult = returnCode;
3337 mDone.set(true);
3338 mDone.notifyAll();
3339 }
3340 }
3341 }
3342
Christopher Tate75a99702011-05-18 16:28:19 -07003343 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003344 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003345
3346 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3347 boolean okay = true;
3348
3349 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3350
3351 // The file content is an .apk file. Copy it out to a staging location and
3352 // attempt to install it.
3353 File apkFile = new File(mDataDir, info.packageName);
3354 try {
3355 FileOutputStream apkStream = new FileOutputStream(apkFile);
3356 byte[] buffer = new byte[32 * 1024];
3357 long size = info.size;
3358 while (size > 0) {
3359 long toRead = (buffer.length < size) ? buffer.length : size;
3360 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003361 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003362 apkStream.write(buffer, 0, didRead);
3363 size -= didRead;
3364 }
3365 apkStream.close();
3366
3367 // make sure the installer can read it
3368 apkFile.setReadable(true, false);
3369
3370 // Now install it
3371 Uri packageUri = Uri.fromFile(apkFile);
3372 mInstallObserver.reset();
3373 mPackageManager.installPackage(packageUri, mInstallObserver,
3374 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
3375 mInstallObserver.waitForCompletion();
3376
3377 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3378 // The only time we continue to accept install of data even if the
3379 // apk install failed is if we had already determined that we could
3380 // accept the data regardless.
3381 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3382 okay = false;
3383 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003384 } else {
3385 // Okay, the install succeeded. Make sure it was the right app.
3386 boolean uninstall = false;
3387 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3388 Slog.w(TAG, "Restore stream claimed to include apk for "
3389 + info.packageName + " but apk was really "
3390 + mInstallObserver.mPackageName);
3391 // delete the package we just put in place; it might be fraudulent
3392 okay = false;
3393 uninstall = true;
3394 } else {
3395 try {
3396 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3397 PackageManager.GET_SIGNATURES);
3398 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3399 Slog.w(TAG, "Restore stream contains apk of package "
3400 + info.packageName + " but it disallows backup/restore");
3401 okay = false;
3402 } else {
3403 // So far so good -- do the signatures match the manifest?
3404 Signature[] sigs = mManifestSignatures.get(info.packageName);
3405 if (!signaturesMatch(sigs, pkg)) {
3406 Slog.w(TAG, "Installed app " + info.packageName
3407 + " signatures do not match restore manifest");
3408 okay = false;
3409 uninstall = true;
3410 }
3411 }
3412 } catch (NameNotFoundException e) {
3413 Slog.w(TAG, "Install of package " + info.packageName
3414 + " succeeded but now not found");
3415 okay = false;
3416 }
3417 }
3418
3419 // If we're not okay at this point, we need to delete the package
3420 // that we just installed.
3421 if (uninstall) {
3422 mDeleteObserver.reset();
3423 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3424 mDeleteObserver, 0);
3425 mDeleteObserver.waitForCompletion();
3426 }
Christopher Tate75a99702011-05-18 16:28:19 -07003427 }
3428 } catch (IOException e) {
3429 Slog.e(TAG, "Unable to transcribe restored apk for install");
3430 okay = false;
3431 } finally {
3432 apkFile.delete();
3433 }
3434
3435 return okay;
3436 }
3437
3438 // Given an actual file content size, consume the post-content padding mandated
3439 // by the tar format.
3440 void skipTarPadding(long size, InputStream instream) throws IOException {
3441 long partial = (size + 512) % 512;
3442 if (partial > 0) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003443 final int needed = 512 - (int)partial;
3444 byte[] buffer = new byte[needed];
3445 if (readExactly(instream, buffer, 0, needed) == needed) {
3446 mBytes += needed;
3447 } else throw new IOException("Unexpected EOF in padding");
Christopher Tate75a99702011-05-18 16:28:19 -07003448 }
3449 }
3450
3451 // Returns a policy constant; takes a buffer arg to reduce memory churn
3452 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3453 throws IOException {
3454 // Fail on suspiciously large manifest files
3455 if (info.size > 64 * 1024) {
3456 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3457 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003458
Christopher Tate75a99702011-05-18 16:28:19 -07003459 byte[] buffer = new byte[(int) info.size];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003460 if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
3461 mBytes += info.size;
3462 } else throw new IOException("Unexpected EOF in manifest");
Christopher Tate75a99702011-05-18 16:28:19 -07003463
3464 RestorePolicy policy = RestorePolicy.IGNORE;
3465 String[] str = new String[1];
3466 int offset = 0;
3467
3468 try {
3469 offset = extractLine(buffer, offset, str);
3470 int version = Integer.parseInt(str[0]);
3471 if (version == BACKUP_MANIFEST_VERSION) {
3472 offset = extractLine(buffer, offset, str);
3473 String manifestPackage = str[0];
3474 // TODO: handle <original-package>
3475 if (manifestPackage.equals(info.packageName)) {
3476 offset = extractLine(buffer, offset, str);
3477 version = Integer.parseInt(str[0]); // app version
3478 offset = extractLine(buffer, offset, str);
3479 int platformVersion = Integer.parseInt(str[0]);
3480 offset = extractLine(buffer, offset, str);
3481 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3482 offset = extractLine(buffer, offset, str);
3483 boolean hasApk = str[0].equals("1");
3484 offset = extractLine(buffer, offset, str);
3485 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003486 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003487 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003488 for (int i = 0; i < numSigs; i++) {
3489 offset = extractLine(buffer, offset, str);
3490 sigs[i] = new Signature(str[0]);
3491 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003492 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003493
3494 // Okay, got the manifest info we need...
3495 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003496 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3497 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003498 // Fall through to IGNORE if the app explicitly disallows backup
3499 final int flags = pkgInfo.applicationInfo.flags;
3500 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3501 // Verify signatures against any installed version; if they
3502 // don't match, then we fall though and ignore the data. The
3503 // signatureMatch() method explicitly ignores the signature
3504 // check for packages installed on the system partition, because
3505 // such packages are signed with the platform cert instead of
3506 // the app developer's cert, so they're different on every
3507 // device.
3508 if (signaturesMatch(sigs, pkgInfo)) {
3509 if (pkgInfo.versionCode >= version) {
3510 Slog.i(TAG, "Sig + version match; taking data");
3511 policy = RestorePolicy.ACCEPT;
3512 } else {
3513 // The data is from a newer version of the app than
3514 // is presently installed. That means we can only
3515 // use it if the matching apk is also supplied.
3516 Slog.d(TAG, "Data version " + version
3517 + " is newer than installed version "
3518 + pkgInfo.versionCode + " - requiring apk");
3519 policy = RestorePolicy.ACCEPT_IF_APK;
3520 }
Christopher Tate75a99702011-05-18 16:28:19 -07003521 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003522 Slog.w(TAG, "Restore manifest signatures do not match "
3523 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003524 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003525 } else {
3526 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3527 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003528 }
3529 } catch (NameNotFoundException e) {
3530 // Okay, the target app isn't installed. We can process
3531 // the restore properly only if the dataset provides the
3532 // apk file and we can successfully install it.
3533 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3534 + " not installed; requiring apk in dataset");
3535 policy = RestorePolicy.ACCEPT_IF_APK;
3536 }
3537
3538 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3539 Slog.i(TAG, "Cannot restore package " + info.packageName
3540 + " without the matching .apk");
3541 }
3542 } else {
3543 Slog.i(TAG, "Missing signature on backed-up package "
3544 + info.packageName);
3545 }
3546 } else {
3547 Slog.i(TAG, "Expected package " + info.packageName
3548 + " but restore manifest claims " + manifestPackage);
3549 }
3550 } else {
3551 Slog.i(TAG, "Unknown restore manifest version " + version
3552 + " for package " + info.packageName);
3553 }
3554 } catch (NumberFormatException e) {
3555 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
Kenny Root11373412011-07-28 15:13:33 -07003556 } catch (IllegalArgumentException e) {
3557 Slog.w(TAG, e.getMessage());
Christopher Tate75a99702011-05-18 16:28:19 -07003558 }
3559
3560 return policy;
3561 }
3562
3563 // Builds a line from a byte buffer starting at 'offset', and returns
3564 // the index of the next unconsumed data in the buffer.
3565 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3566 final int end = buffer.length;
3567 if (offset >= end) throw new IOException("Incomplete data");
3568
3569 int pos;
3570 for (pos = offset; pos < end; pos++) {
3571 byte c = buffer[pos];
3572 // at LF we declare end of line, and return the next char as the
3573 // starting point for the next time through
3574 if (c == '\n') {
3575 break;
3576 }
3577 }
3578 outStr[0] = new String(buffer, offset, pos - offset);
3579 pos++; // may be pointing an extra byte past the end but that's okay
3580 return pos;
3581 }
3582
3583 void dumpFileMetadata(FileMetadata info) {
3584 if (DEBUG) {
3585 StringBuilder b = new StringBuilder(128);
3586
3587 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003588 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003589 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3590 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3591 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3592 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3593 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3594 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3595 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3596 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3597 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3598 b.append(String.format(" %9d ", info.size));
3599
3600 Date stamp = new Date(info.mtime);
3601 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3602
3603 b.append(info.packageName);
3604 b.append(" :: ");
3605 b.append(info.domain);
3606 b.append(" :: ");
3607 b.append(info.path);
3608
3609 Slog.i(TAG, b.toString());
3610 }
3611 }
3612 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3613 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3614 byte[] block = new byte[512];
3615 FileMetadata info = null;
3616
3617 boolean gotHeader = readTarHeader(instream, block);
3618 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003619 try {
3620 // okay, presume we're okay, and extract the various metadata
3621 info = new FileMetadata();
3622 info.size = extractRadix(block, 124, 12, 8);
3623 info.mtime = extractRadix(block, 136, 12, 8);
3624 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003625
Christopher Tate2efd2db2011-07-19 16:32:49 -07003626 info.path = extractString(block, 345, 155); // prefix
3627 String path = extractString(block, 0, 100);
3628 if (path.length() > 0) {
3629 if (info.path.length() > 0) info.path += '/';
3630 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003631 }
Christopher Tate75a99702011-05-18 16:28:19 -07003632
Christopher Tate2efd2db2011-07-19 16:32:49 -07003633 // tar link indicator field: 1 byte at offset 156 in the header.
3634 int typeChar = block[156];
3635 if (typeChar == 'x') {
3636 // pax extended header, so we need to read that
3637 gotHeader = readPaxExtendedHeader(instream, info);
3638 if (gotHeader) {
3639 // and after a pax extended header comes another real header -- read
3640 // that to find the real file type
3641 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003642 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003643 if (!gotHeader) throw new IOException("Bad or missing pax header");
3644
3645 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003646 }
Christopher Tate75a99702011-05-18 16:28:19 -07003647
Christopher Tate2efd2db2011-07-19 16:32:49 -07003648 switch (typeChar) {
3649 case '0': info.type = BackupAgent.TYPE_FILE; break;
3650 case '5': {
3651 info.type = BackupAgent.TYPE_DIRECTORY;
3652 if (info.size != 0) {
3653 Slog.w(TAG, "Directory entry with nonzero size in header");
3654 info.size = 0;
3655 }
3656 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003657 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003658 case 0: {
3659 // presume EOF
3660 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3661 return null;
3662 }
3663 default: {
3664 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3665 throw new IOException("Unknown entity type " + typeChar);
3666 }
Christopher Tate75a99702011-05-18 16:28:19 -07003667 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003668
3669 // Parse out the path
3670 //
3671 // first: apps/shared/unrecognized
3672 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3673 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3674 // File in shared storage. !!! TODO: implement this.
3675 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3676 info.packageName = "com.android.sharedstoragebackup";
3677 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3678 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3679 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3680 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3681 // App content! Parse out the package name and domain
3682
3683 // strip the apps/ prefix
3684 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3685
3686 // extract the package name
3687 int slash = info.path.indexOf('/');
3688 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3689 info.packageName = info.path.substring(0, slash);
3690 info.path = info.path.substring(slash+1);
3691
3692 // if it's a manifest we're done, otherwise parse out the domains
3693 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3694 slash = info.path.indexOf('/');
3695 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3696 info.domain = info.path.substring(0, slash);
3697 // validate that it's one of the domains we understand
3698 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3699 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3700 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3701 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3702 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3703 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3704 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3705 throw new IOException("Unrecognized domain " + info.domain);
3706 }
3707
3708 info.path = info.path.substring(slash + 1);
3709 }
3710 }
3711 } catch (IOException e) {
3712 if (DEBUG) {
Christopher Tate6853fcf2011-08-10 17:52:21 -07003713 Slog.e(TAG, "Parse error in header: " + e.getMessage());
Christopher Tate2efd2db2011-07-19 16:32:49 -07003714 HEXLOG(block);
3715 }
3716 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003717 }
3718 }
3719 return info;
3720 }
3721
Christopher Tate2efd2db2011-07-19 16:32:49 -07003722 private void HEXLOG(byte[] block) {
3723 int offset = 0;
3724 int todo = block.length;
3725 StringBuilder buf = new StringBuilder(64);
3726 while (todo > 0) {
3727 buf.append(String.format("%04x ", offset));
3728 int numThisLine = (todo > 16) ? 16 : todo;
3729 for (int i = 0; i < numThisLine; i++) {
3730 buf.append(String.format("%02x ", block[offset+i]));
3731 }
3732 Slog.i("hexdump", buf.toString());
3733 buf.setLength(0);
3734 todo -= numThisLine;
3735 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003736 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003737 }
3738
Christopher Tate6853fcf2011-08-10 17:52:21 -07003739 // Read exactly the given number of bytes into a buffer at the stated offset.
3740 // Returns false if EOF is encountered before the requested number of bytes
3741 // could be read.
3742 int readExactly(InputStream in, byte[] buffer, int offset, int size)
3743 throws IOException {
3744 if (size <= 0) throw new IllegalArgumentException("size must be > 0");
3745
3746 int soFar = 0;
3747 while (soFar < size) {
3748 int nRead = in.read(buffer, offset + soFar, size - soFar);
3749 if (nRead <= 0) {
3750 if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
3751 break;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003752 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003753 soFar += nRead;
Christopher Tate2efd2db2011-07-19 16:32:49 -07003754 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003755 return soFar;
3756 }
3757
3758 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3759 final int got = readExactly(instream, block, 0, 512);
3760 if (got == 0) return false; // Clean EOF
3761 if (got < 512) throw new IOException("Unable to read full block header");
3762 mBytes += 512;
3763 return true;
Christopher Tate75a99702011-05-18 16:28:19 -07003764 }
3765
3766 // overwrites 'info' fields based on the pax extended header
3767 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3768 throws IOException {
3769 // We should never see a pax extended header larger than this
3770 if (info.size > 32*1024) {
3771 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3772 + " - aborting");
3773 throw new IOException("Sanity failure: pax header size " + info.size);
3774 }
3775
3776 // read whole blocks, not just the content size
3777 int numBlocks = (int)((info.size + 511) >> 9);
3778 byte[] data = new byte[numBlocks * 512];
Christopher Tate6853fcf2011-08-10 17:52:21 -07003779 if (readExactly(instream, data, 0, data.length) < data.length) {
3780 throw new IOException("Unable to read full pax header");
Christopher Tate75a99702011-05-18 16:28:19 -07003781 }
Christopher Tate6853fcf2011-08-10 17:52:21 -07003782 mBytes += data.length;
Christopher Tate75a99702011-05-18 16:28:19 -07003783
3784 final int contentSize = (int) info.size;
3785 int offset = 0;
3786 do {
3787 // extract the line at 'offset'
3788 int eol = offset+1;
3789 while (eol < contentSize && data[eol] != ' ') eol++;
3790 if (eol >= contentSize) {
3791 // error: we just hit EOD looking for the end of the size field
3792 throw new IOException("Invalid pax data");
3793 }
3794 // eol points to the space between the count and the key
3795 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3796 int key = eol + 1; // start of key=value
3797 eol = offset + linelen - 1; // trailing LF
3798 int value;
3799 for (value = key+1; data[value] != '=' && value <= eol; value++);
3800 if (value > eol) {
3801 throw new IOException("Invalid pax declaration");
3802 }
3803
3804 // pax requires that key/value strings be in UTF-8
3805 String keyStr = new String(data, key, value-key, "UTF-8");
3806 // -1 to strip the trailing LF
3807 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3808
3809 if ("path".equals(keyStr)) {
3810 info.path = valStr;
3811 } else if ("size".equals(keyStr)) {
3812 info.size = Long.parseLong(valStr);
3813 } else {
3814 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3815 }
3816
3817 offset += linelen;
3818 } while (offset < contentSize);
3819
3820 return true;
3821 }
3822
3823 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3824 throws IOException {
3825 long value = 0;
3826 final int end = offset + maxChars;
3827 for (int i = offset; i < end; i++) {
3828 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003829 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003830 if (b == 0 || b == ' ') break;
3831 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003832 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003833 }
3834 value = radix * value + (b - '0');
3835 }
3836 return value;
3837 }
3838
3839 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3840 final int end = offset + maxChars;
3841 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003842 // tar string fields terminate early with a NUL
3843 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003844 return new String(data, offset, eos-offset, "US-ASCII");
3845 }
3846
3847 void sendStartRestore() {
3848 if (mObserver != null) {
3849 try {
3850 mObserver.onStartRestore();
3851 } catch (RemoteException e) {
3852 Slog.w(TAG, "full restore observer went away: startRestore");
3853 mObserver = null;
3854 }
3855 }
3856 }
3857
3858 void sendOnRestorePackage(String name) {
3859 if (mObserver != null) {
3860 try {
3861 // TODO: use a more user-friendly name string
3862 mObserver.onRestorePackage(name);
3863 } catch (RemoteException e) {
3864 Slog.w(TAG, "full restore observer went away: restorePackage");
3865 mObserver = null;
3866 }
3867 }
3868 }
3869
3870 void sendEndRestore() {
3871 if (mObserver != null) {
3872 try {
3873 mObserver.onEndRestore();
3874 } catch (RemoteException e) {
3875 Slog.w(TAG, "full restore observer went away: endRestore");
3876 mObserver = null;
3877 }
3878 }
3879 }
3880 }
3881
Christopher Tatedf01dea2009-06-09 20:45:02 -07003882 // ----- Restore handling -----
3883
Christopher Tate78dd4a72009-11-04 11:49:08 -08003884 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3885 // If the target resides on the system partition, we allow it to restore
3886 // data from the like-named package in a restore set even if the signatures
3887 // do not match. (Unlike general applications, those flashed to the system
3888 // partition will be signed with the device's platform certificate, so on
3889 // different phones the same system app will have different signatures.)
3890 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003891 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003892 return true;
3893 }
3894
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003895 // Allow unsigned apps, but not signed on one device and unsigned on the other
3896 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003897 Signature[] deviceSigs = target.signatures;
Christopher Tatec58efa62011-08-01 19:20:14 -07003898 if (MORE_DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003899 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003900 if ((storedSigs == null || storedSigs.length == 0)
3901 && (deviceSigs == null || deviceSigs.length == 0)) {
3902 return true;
3903 }
3904 if (storedSigs == null || deviceSigs == null) {
3905 return false;
3906 }
3907
Christopher Tateabce4e82009-06-18 18:35:32 -07003908 // !!! TODO: this demands that every stored signature match one
3909 // that is present on device, and does not demand the converse.
3910 // Is this this right policy?
3911 int nStored = storedSigs.length;
3912 int nDevice = deviceSigs.length;
3913
3914 for (int i=0; i < nStored; i++) {
3915 boolean match = false;
3916 for (int j=0; j < nDevice; j++) {
3917 if (storedSigs[i].equals(deviceSigs[j])) {
3918 match = true;
3919 break;
3920 }
3921 }
3922 if (!match) {
3923 return false;
3924 }
3925 }
3926 return true;
3927 }
3928
Christopher Tate2982d062011-09-06 20:35:24 -07003929 enum RestoreState {
3930 INITIAL,
3931 DOWNLOAD_DATA,
3932 PM_METADATA,
3933 RUNNING_QUEUE,
3934 FINAL
3935 }
3936
3937 class PerformRestoreTask implements BackupRestoreTask {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003938 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003939 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003940 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003941 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003942 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003943 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003944 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003945 private HashSet<String> mFilterSet;
Christopher Tate2982d062011-09-06 20:35:24 -07003946 private long mStartRealtime;
3947 private PackageManagerBackupAgent mPmAgent;
3948 private List<PackageInfo> mAgentPackages;
3949 private ArrayList<PackageInfo> mRestorePackages;
3950 private RestoreState mCurrentState;
3951 private int mCount;
3952 private boolean mFinished;
3953 private int mStatus;
3954 private File mBackupDataName;
3955 private File mNewStateName;
3956 private File mSavedStateName;
3957 private ParcelFileDescriptor mBackupData;
3958 private ParcelFileDescriptor mNewState;
3959 private PackageInfo mCurrentPackage;
3960
Christopher Tatedf01dea2009-06-09 20:45:02 -07003961
Christopher Tate5cbbf562009-06-22 16:44:51 -07003962 class RestoreRequest {
3963 public PackageInfo app;
3964 public int storedAppVersion;
3965
3966 RestoreRequest(PackageInfo _app, int _version) {
3967 app = _app;
3968 storedAppVersion = _version;
3969 }
3970 }
3971
Christopher Tate44a27902010-01-27 17:15:49 -08003972 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003973 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003974 boolean needFullBackup, String[] filterSet) {
Christopher Tate2982d062011-09-06 20:35:24 -07003975 mCurrentState = RestoreState.INITIAL;
3976 mFinished = false;
3977 mPmAgent = null;
3978
Christopher Tatedf01dea2009-06-09 20:45:02 -07003979 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003980 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003981 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003982 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003983 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003984 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003985
Christopher Tate284f1bb2011-07-07 14:31:18 -07003986 if (filterSet != null) {
3987 mFilterSet = new HashSet<String>();
3988 for (String pkg : filterSet) {
3989 mFilterSet.add(pkg);
3990 }
3991 } else {
3992 mFilterSet = null;
3993 }
3994
Christopher Tate5cb400b2009-06-25 16:03:14 -07003995 try {
3996 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3997 } catch (RemoteException e) {
3998 // can't happen; the transport is local
3999 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004000 }
4001
Christopher Tate2982d062011-09-06 20:35:24 -07004002 // Execute one tick of whatever state machine the task implements
4003 @Override
4004 public void execute() {
4005 if (MORE_DEBUG) Slog.v(TAG, "*** Executing restore step: " + mCurrentState);
4006 switch (mCurrentState) {
4007 case INITIAL:
4008 beginRestore();
4009 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07004010
Christopher Tate2982d062011-09-06 20:35:24 -07004011 case DOWNLOAD_DATA:
4012 downloadRestoreData();
4013 break;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004014
Christopher Tate2982d062011-09-06 20:35:24 -07004015 case PM_METADATA:
4016 restorePmMetadata();
4017 break;
4018
4019 case RUNNING_QUEUE:
4020 restoreNextAgent();
4021 break;
4022
4023 case FINAL:
4024 if (!mFinished) finalizeRestore();
4025 else {
4026 Slog.e(TAG, "Duplicate finish");
4027 }
4028 mFinished = true;
4029 break;
4030 }
4031 }
4032
4033 // Initialize and set up for the PM metadata restore, which comes first
4034 void beginRestore() {
4035 // Don't account time doing the restore as inactivity of the app
4036 // that has opened a restore session.
4037 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4038
4039 // Assume error until we successfully init everything
4040 mStatus = BackupConstants.TRANSPORT_ERROR;
4041
Christopher Tatedf01dea2009-06-09 20:45:02 -07004042 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07004043 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004044 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07004045
Dan Egnorefe52642009-06-24 00:16:33 -07004046 // Get the list of all packages which have backup enabled.
4047 // (Include the Package Manager metadata pseudo-package first.)
Christopher Tate2982d062011-09-06 20:35:24 -07004048 mRestorePackages = new ArrayList<PackageInfo>();
Dan Egnorefe52642009-06-24 00:16:33 -07004049 PackageInfo omPackage = new PackageInfo();
4050 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate2982d062011-09-06 20:35:24 -07004051 mRestorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004052
Christopher Tate2982d062011-09-06 20:35:24 -07004053 mAgentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08004054 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004055 // if there's a filter set, strip out anything that isn't
4056 // present before proceeding
4057 if (mFilterSet != null) {
Christopher Tate2982d062011-09-06 20:35:24 -07004058 for (int i = mAgentPackages.size() - 1; i >= 0; i--) {
4059 final PackageInfo pkg = mAgentPackages.get(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004060 if (! mFilterSet.contains(pkg.packageName)) {
Christopher Tate2982d062011-09-06 20:35:24 -07004061 mAgentPackages.remove(i);
Christopher Tate284f1bb2011-07-07 14:31:18 -07004062 }
4063 }
Christopher Tate2982d062011-09-06 20:35:24 -07004064 if (MORE_DEBUG) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004065 Slog.i(TAG, "Post-filter package set for restore:");
Christopher Tate2982d062011-09-06 20:35:24 -07004066 for (PackageInfo p : mAgentPackages) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07004067 Slog.i(TAG, " " + p);
4068 }
4069 }
4070 }
Christopher Tate2982d062011-09-06 20:35:24 -07004071 mRestorePackages.addAll(mAgentPackages);
Christopher Tate84725812010-02-04 15:52:40 -08004072 } else {
4073 // Just one package to attempt restore of
Christopher Tate2982d062011-09-06 20:35:24 -07004074 mRestorePackages.add(mTargetPackage);
Christopher Tate84725812010-02-04 15:52:40 -08004075 }
Dan Egnorefe52642009-06-24 00:16:33 -07004076
Christopher Tate7d562ec2009-06-25 18:03:43 -07004077 // let the observer know that we're running
4078 if (mObserver != null) {
4079 try {
4080 // !!! TODO: get an actual count from the transport after
4081 // its startRestore() runs?
Christopher Tate2982d062011-09-06 20:35:24 -07004082 mObserver.restoreStarting(mRestorePackages.size());
Christopher Tate7d562ec2009-06-25 18:03:43 -07004083 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004084 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07004085 mObserver = null;
4086 }
4087 }
Christopher Tate2982d062011-09-06 20:35:24 -07004088 } catch (RemoteException e) {
4089 // Something has gone catastrophically wrong with the transport
4090 Slog.e(TAG, "Error communicating with transport for restore");
4091 executeNextState(RestoreState.FINAL);
4092 return;
4093 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004094
Christopher Tate2982d062011-09-06 20:35:24 -07004095 mStatus = BackupConstants.TRANSPORT_OK;
4096 executeNextState(RestoreState.DOWNLOAD_DATA);
4097 }
4098
4099 void downloadRestoreData() {
4100 // Note that the download phase can be very time consuming, but we're executing
4101 // it inline here on the looper. This is "okay" because it is not calling out to
4102 // third party code; the transport is "trusted," and so we assume it is being a
4103 // good citizen and timing out etc when appropriate.
4104 //
4105 // TODO: when appropriate, move the download off the looper and rearrange the
4106 // error handling around that.
4107 try {
4108 mStatus = mTransport.startRestore(mToken,
4109 mRestorePackages.toArray(new PackageInfo[0]));
4110 if (mStatus != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004111 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004112 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004113 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004114 return;
4115 }
Christopher Tate2982d062011-09-06 20:35:24 -07004116 } catch (RemoteException e) {
4117 Slog.e(TAG, "Error communicating with transport for restore");
4118 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4119 mStatus = BackupConstants.TRANSPORT_ERROR;
4120 executeNextState(RestoreState.FINAL);
4121 return;
4122 }
Dan Egnorefe52642009-06-24 00:16:33 -07004123
Christopher Tate2982d062011-09-06 20:35:24 -07004124 // Successful download of the data to be parceled out to the apps, so off we go.
4125 executeNextState(RestoreState.PM_METADATA);
4126 }
4127
4128 void restorePmMetadata() {
4129 try {
Dan Egnorefe52642009-06-24 00:16:33 -07004130 String packageName = mTransport.nextRestorePackage();
4131 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004132 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004133 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate2982d062011-09-06 20:35:24 -07004134 mStatus = BackupConstants.TRANSPORT_ERROR;
4135 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004136 return;
4137 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004138 Slog.i(TAG, "No restore data available");
Christopher Tate2982d062011-09-06 20:35:24 -07004139 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004140 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Christopher Tate2982d062011-09-06 20:35:24 -07004141 mStatus = BackupConstants.TRANSPORT_OK;
4142 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004143 return;
4144 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004145 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Christopher Tate2982d062011-09-06 20:35:24 -07004146 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004147 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004148 "Package manager data missing");
Christopher Tate2982d062011-09-06 20:35:24 -07004149 executeNextState(RestoreState.FINAL);
Dan Egnorefe52642009-06-24 00:16:33 -07004150 return;
4151 }
4152
4153 // Pull the Package Manager metadata from the restore set first
Christopher Tate2982d062011-09-06 20:35:24 -07004154 PackageInfo omPackage = new PackageInfo();
4155 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
4156 mPmAgent = new PackageManagerBackupAgent(
4157 mPackageManager, mAgentPackages);
4158 initiateOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(mPmAgent.onBind()),
Chris Tate249345b2010-10-29 12:57:04 -07004159 mNeedFullBackup);
Christopher Tate2982d062011-09-06 20:35:24 -07004160 // The PM agent called operationComplete() already, because our invocation
4161 // of it is process-local and therefore synchronous. That means that a
4162 // RUNNING_QUEUE message is already enqueued. Only if we're unable to
4163 // proceed with running the queue do we remove that pending message and
4164 // jump straight to the FINAL state.
Dan Egnorefe52642009-06-24 00:16:33 -07004165
Christopher Tate8c032472009-07-02 14:28:47 -07004166 // Verify that the backup set includes metadata. If not, we can't do
4167 // signature/version verification etc, so we simply do not proceed with
4168 // the restore operation.
Christopher Tate2982d062011-09-06 20:35:24 -07004169 if (!mPmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004170 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004171 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Christopher Tate2982d062011-09-06 20:35:24 -07004172 "Package manager restore metadata missing");
4173 mStatus = BackupConstants.TRANSPORT_ERROR;
4174 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4175 executeNextState(RestoreState.FINAL);
Christopher Tate8c032472009-07-02 14:28:47 -07004176 return;
4177 }
Christopher Tate2982d062011-09-06 20:35:24 -07004178 } catch (RemoteException e) {
4179 Slog.e(TAG, "Error communicating with transport for restore");
4180 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4181 mStatus = BackupConstants.TRANSPORT_ERROR;
4182 mBackupHandler.removeMessages(MSG_BACKUP_RESTORE_STEP, this);
4183 executeNextState(RestoreState.FINAL);
4184 return;
4185 }
Christopher Tate8c032472009-07-02 14:28:47 -07004186
Christopher Tate2982d062011-09-06 20:35:24 -07004187 // Metadata is intact, so we can now run the restore queue. If we get here,
4188 // we have already enqueued the necessary next-step message on the looper.
4189 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07004190
Christopher Tate2982d062011-09-06 20:35:24 -07004191 void restoreNextAgent() {
4192 try {
4193 String packageName = mTransport.nextRestorePackage();
Christopher Tatedf01dea2009-06-09 20:45:02 -07004194
Christopher Tate2982d062011-09-06 20:35:24 -07004195 if (packageName == null) {
4196 Slog.e(TAG, "Error getting next restore package");
4197 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
4198 executeNextState(RestoreState.FINAL);
4199 return;
4200 } else if (packageName.equals("")) {
4201 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
4202 int millis = (int) (SystemClock.elapsedRealtime() - mStartRealtime);
4203 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, mCount, millis);
4204 executeNextState(RestoreState.FINAL);
4205 return;
Dan Egnorefe52642009-06-24 00:16:33 -07004206 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07004207
4208 if (mObserver != null) {
4209 try {
Christopher Tate2982d062011-09-06 20:35:24 -07004210 mObserver.onUpdate(mCount, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07004211 } catch (RemoteException e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004212 Slog.d(TAG, "Restore observer died in onUpdate");
4213 mObserver = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07004214 }
4215 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004216
Christopher Tate2982d062011-09-06 20:35:24 -07004217 Metadata metaInfo = mPmAgent.getRestoredMetadata(packageName);
4218 if (metaInfo == null) {
4219 Slog.e(TAG, "Missing metadata for " + packageName);
4220 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4221 "Package metadata missing");
4222 executeNextState(RestoreState.RUNNING_QUEUE);
4223 return;
Christopher Tate84725812010-02-04 15:52:40 -08004224 }
4225
Christopher Tate2982d062011-09-06 20:35:24 -07004226 PackageInfo packageInfo;
4227 try {
4228 int flags = PackageManager.GET_SIGNATURES;
4229 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
4230 } catch (NameNotFoundException e) {
4231 Slog.e(TAG, "Invalid package restoring data", e);
4232 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4233 "Package missing on device");
4234 executeNextState(RestoreState.RUNNING_QUEUE);
4235 return;
Christopher Tate1bb69062010-02-19 17:02:12 -08004236 }
4237
Christopher Tate2982d062011-09-06 20:35:24 -07004238 if (metaInfo.versionCode > packageInfo.versionCode) {
4239 // Data is from a "newer" version of the app than we have currently
4240 // installed. If the app has not declared that it is prepared to
4241 // handle this case, we do not attempt the restore.
4242 if ((packageInfo.applicationInfo.flags
4243 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
4244 String message = "Version " + metaInfo.versionCode
4245 + " > installed version " + packageInfo.versionCode;
4246 Slog.w(TAG, "Package " + packageName + ": " + message);
4247 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4248 packageName, message);
4249 executeNextState(RestoreState.RUNNING_QUEUE);
4250 return;
4251 } else {
4252 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
4253 + " > installed " + packageInfo.versionCode
4254 + " but restoreAnyVersion");
4255 }
4256 }
Christopher Tate73a3cb32010-12-13 18:27:26 -08004257
Christopher Tate2982d062011-09-06 20:35:24 -07004258 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
4259 Slog.w(TAG, "Signature mismatch restoring " + packageName);
4260 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4261 "Signature mismatch");
4262 executeNextState(RestoreState.RUNNING_QUEUE);
4263 return;
4264 }
4265
4266 if (DEBUG) Slog.v(TAG, "Package " + packageName
4267 + " restore version [" + metaInfo.versionCode
4268 + "] is compatible with installed version ["
4269 + packageInfo.versionCode + "]");
4270
4271 // Then set up and bind the agent
4272 IBackupAgent agent = bindToAgentSynchronous(
4273 packageInfo.applicationInfo,
4274 IApplicationThread.BACKUP_MODE_INCREMENTAL);
4275 if (agent == null) {
4276 Slog.w(TAG, "Can't find backup agent for " + packageName);
4277 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
4278 "Restore agent missing");
4279 executeNextState(RestoreState.RUNNING_QUEUE);
4280 return;
4281 }
4282
4283 // And then finally start the restore on this agent
4284 try {
4285 initiateOneRestore(packageInfo, metaInfo.versionCode, agent, mNeedFullBackup);
4286 ++mCount;
4287 } catch (Exception e) {
4288 Slog.e(TAG, "Error when attempting restore: " + e.toString());
4289 agentErrorCleanup();
4290 executeNextState(RestoreState.RUNNING_QUEUE);
4291 }
4292 } catch (RemoteException e) {
4293 Slog.e(TAG, "Unable to fetch restore data from transport");
4294 mStatus = BackupConstants.TRANSPORT_ERROR;
4295 executeNextState(RestoreState.FINAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004296 }
4297 }
4298
Christopher Tate2982d062011-09-06 20:35:24 -07004299 void finalizeRestore() {
4300 if (MORE_DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
4301
4302 try {
4303 mTransport.finishRestore();
4304 } catch (RemoteException e) {
4305 Slog.e(TAG, "Error finishing restore", e);
4306 }
4307
4308 if (mObserver != null) {
4309 try {
4310 mObserver.restoreFinished(mStatus);
4311 } catch (RemoteException e) {
4312 Slog.d(TAG, "Restore observer died at restoreFinished");
4313 }
4314 }
4315
4316 // If this was a restoreAll operation, record that this was our
4317 // ancestral dataset, as well as the set of apps that are possibly
4318 // restoreable from the dataset
4319 if (mTargetPackage == null && mPmAgent != null) {
4320 mAncestralPackages = mPmAgent.getRestoredPackages();
4321 mAncestralToken = mToken;
4322 writeRestoreTokens();
4323 }
4324
4325 // We must under all circumstances tell the Package Manager to
4326 // proceed with install notifications if it's waiting for us.
4327 if (mPmToken > 0) {
4328 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
4329 try {
4330 mPackageManagerBinder.finishPackageInstall(mPmToken);
4331 } catch (RemoteException e) { /* can't happen */ }
4332 }
4333
4334 // Furthermore we need to reset the session timeout clock
4335 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4336 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
4337 TIMEOUT_RESTORE_INTERVAL);
4338
4339 // done; we can finally release the wakelock
4340 Slog.i(TAG, "Restore complete.");
4341 mWakelock.release();
4342 }
4343
4344 // Call asynchronously into the app, passing it the restore data. The next step
4345 // after this is always a callback, either operationComplete() or handleTimeout().
4346 void initiateOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
Chris Tate249345b2010-10-29 12:57:04 -07004347 boolean needFullBackup) {
Christopher Tate2982d062011-09-06 20:35:24 -07004348 mCurrentPackage = app;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004349 final String packageName = app.packageName;
4350
Christopher Tate2982d062011-09-06 20:35:24 -07004351 if (DEBUG) Slog.d(TAG, "initiateOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004352
Christopher Tatec7b31e32009-06-10 15:49:30 -07004353 // !!! TODO: get the dirs from the transport
Christopher Tate2982d062011-09-06 20:35:24 -07004354 mBackupDataName = new File(mDataDir, packageName + ".restore");
4355 mNewStateName = new File(mStateDir, packageName + ".new");
4356 mSavedStateName = new File(mStateDir, packageName);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004357
Christopher Tate4a627c72011-04-01 14:43:32 -07004358 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004359 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07004360 // Run the transport's restore pass
Christopher Tate2982d062011-09-06 20:35:24 -07004361 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004362 ParcelFileDescriptor.MODE_READ_WRITE |
4363 ParcelFileDescriptor.MODE_CREATE |
4364 ParcelFileDescriptor.MODE_TRUNCATE);
4365
Christopher Tate2982d062011-09-06 20:35:24 -07004366 if (mTransport.getRestoreData(mBackupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004367 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004368 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07004369 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07004370 }
4371
4372 // Okay, we have the data. Now have the agent do the restore.
Christopher Tate2982d062011-09-06 20:35:24 -07004373 mBackupData.close();
4374 mBackupData = ParcelFileDescriptor.open(mBackupDataName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07004375 ParcelFileDescriptor.MODE_READ_ONLY);
4376
Christopher Tate2982d062011-09-06 20:35:24 -07004377 mNewState = ParcelFileDescriptor.open(mNewStateName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07004378 ParcelFileDescriptor.MODE_READ_WRITE |
4379 ParcelFileDescriptor.MODE_CREATE |
4380 ParcelFileDescriptor.MODE_TRUNCATE);
4381
Christopher Tate44a27902010-01-27 17:15:49 -08004382 // Kick off the restore, checking for hung agents
Christopher Tate2982d062011-09-06 20:35:24 -07004383 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, this);
4384 agent.doRestore(mBackupData, appVersionCode, mNewState, token, mBackupManagerBinder);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004385 } catch (Exception e) {
Christopher Tate2982d062011-09-06 20:35:24 -07004386 Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004387 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Christopher Tate2982d062011-09-06 20:35:24 -07004388 agentErrorCleanup(); // clears any pending timeout messages as well
Dan Egnorbb9001c2009-07-27 12:20:13 -07004389
Christopher Tate2982d062011-09-06 20:35:24 -07004390 // After a restore failure we go back to running the queue. If there
4391 // are no more packages to be restored that will be handled by the
4392 // next step.
4393 executeNextState(RestoreState.RUNNING_QUEUE);
4394 }
4395 }
Chris Tate249345b2010-10-29 12:57:04 -07004396
Christopher Tate2982d062011-09-06 20:35:24 -07004397 void agentErrorCleanup() {
4398 // If the agent fails restore, it might have put the app's data
4399 // into an incoherent state. For consistency we wipe its data
4400 // again in this case before continuing with normal teardown
4401 clearApplicationDataSynchronous(mCurrentPackage.packageName);
4402 agentCleanup();
4403 }
4404
4405 void agentCleanup() {
4406 mBackupDataName.delete();
4407 try { if (mBackupData != null) mBackupData.close(); } catch (IOException e) {}
4408 try { if (mNewState != null) mNewState.close(); } catch (IOException e) {}
4409 mBackupData = mNewState = null;
4410
4411 // if everything went okay, remember the recorded state now
4412 //
4413 // !!! TODO: the restored data should be migrated on the server
4414 // side into the current dataset. In that case the new state file
4415 // we just created would reflect the data already extant in the
4416 // backend, so there'd be nothing more to do. Until that happens,
4417 // however, we need to make sure that we record the data to the
4418 // current backend dataset. (Yes, this means shipping the data over
4419 // the wire in both directions. That's bad, but consistency comes
4420 // first, then efficiency.) Once we introduce server-side data
4421 // migration to the newly-restored device's dataset, we will change
4422 // the following from a discard of the newly-written state to the
4423 // "correct" operation of renaming into the canonical state blob.
4424 mNewStateName.delete(); // TODO: remove; see above comment
4425 //mNewStateName.renameTo(mSavedStateName); // TODO: replace with this
4426
4427 // If this wasn't the PM pseudopackage, tear down the agent side
4428 if (mCurrentPackage.applicationInfo != null) {
4429 // unbind and tidy up even on timeout or failure
4430 try {
4431 mActivityManager.unbindBackupAgent(mCurrentPackage.applicationInfo);
4432
4433 // The agent was probably running with a stub Application object,
4434 // which isn't a valid run mode for the main app logic. Shut
4435 // down the app so that next time it's launched, it gets the
4436 // usual full initialization. Note that this is only done for
4437 // full-system restores: when a single app has requested a restore,
4438 // it is explicitly not killed following that operation.
4439 if (mTargetPackage == null && (mCurrentPackage.applicationInfo.flags
4440 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
4441 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
4442 + mCurrentPackage.applicationInfo.processName);
4443 mActivityManager.killApplicationProcess(
4444 mCurrentPackage.applicationInfo.processName,
4445 mCurrentPackage.applicationInfo.uid);
4446 }
4447 } catch (RemoteException e) {
4448 // can't happen; we run in the same process as the activity manager
Chris Tate249345b2010-10-29 12:57:04 -07004449 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004450 }
Christopher Tate2982d062011-09-06 20:35:24 -07004451
4452 // The caller is responsible for reestablishing the state machine; our
4453 // responsibility here is to clear the decks for whatever comes next.
4454 mBackupHandler.removeMessages(MSG_TIMEOUT, this);
4455 synchronized (mCurrentOpLock) {
4456 mCurrentOperations.clear();
4457 }
4458 }
4459
4460 // A call to agent.doRestore() has been positively acknowledged as complete
4461 @Override
4462 public void operationComplete() {
4463 int size = (int) mBackupDataName.length();
4464 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, mCurrentPackage.packageName, size);
4465 // Just go back to running the restore queue
4466 agentCleanup();
4467
4468 executeNextState(RestoreState.RUNNING_QUEUE);
4469 }
4470
4471 // A call to agent.doRestore() has timed out
4472 @Override
4473 public void handleTimeout() {
4474 Slog.e(TAG, "Timeout restoring application " + mCurrentPackage.packageName);
4475 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
4476 mCurrentPackage.packageName, "restore timeout");
4477 // Handle like an agent that threw on invocation: wipe it and go on to the next
4478 agentErrorCleanup();
4479 executeNextState(RestoreState.RUNNING_QUEUE);
4480 }
4481
4482 void executeNextState(RestoreState nextState) {
4483 if (MORE_DEBUG) Slog.i(TAG, " => executing next step on "
4484 + this + " nextState=" + nextState);
4485 mCurrentState = nextState;
4486 Message msg = mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, this);
4487 mBackupHandler.sendMessage(msg);
Christopher Tatedf01dea2009-06-09 20:45:02 -07004488 }
4489 }
4490
Christopher Tate44a27902010-01-27 17:15:49 -08004491 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004492 IBackupTransport mTransport;
4493 PackageInfo mPackage;
4494
Christopher Tate44a27902010-01-27 17:15:49 -08004495 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004496 mTransport = transport;
4497 mPackage = packageInfo;
4498 }
4499
Christopher Tateee0e78a2009-07-02 11:17:03 -07004500 public void run() {
4501 try {
4502 // Clear the on-device backup state to ensure a full backup next time
4503 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4504 File stateFile = new File(stateDir, mPackage.packageName);
4505 stateFile.delete();
4506
4507 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004508 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004509 mTransport.clearBackupData(mPackage);
4510 } catch (RemoteException e) {
4511 // can't happen; the transport is local
4512 } finally {
4513 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004514 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004515 mTransport.finishBackup();
4516 } catch (RemoteException e) {
4517 // can't happen; the transport is local
4518 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004519
4520 // Last but not least, release the cpu
4521 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004522 }
4523 }
4524 }
4525
Christopher Tate44a27902010-01-27 17:15:49 -08004526 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004527 HashSet<String> mQueue;
4528
Christopher Tate44a27902010-01-27 17:15:49 -08004529 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004530 mQueue = transportNames;
4531 }
4532
Christopher Tate4cc86e12009-09-21 19:36:51 -07004533 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004534 try {
4535 for (String transportName : mQueue) {
4536 IBackupTransport transport = getTransport(transportName);
4537 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004538 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004539 continue;
4540 }
4541
Joe Onorato8a9b2202010-02-26 18:56:32 -08004542 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004543 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004544 long startRealtime = SystemClock.elapsedRealtime();
4545 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004546
Christopher Tate4cc86e12009-09-21 19:36:51 -07004547 if (status == BackupConstants.TRANSPORT_OK) {
4548 status = transport.finishBackup();
4549 }
4550
4551 // Okay, the wipe really happened. Clean up our local bookkeeping.
4552 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004553 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004554 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004555 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004556 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004557 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004558 synchronized (mQueueLock) {
4559 recordInitPendingLocked(false, transportName);
4560 }
Dan Egnor726247c2009-09-29 19:12:31 -07004561 } else {
4562 // If this didn't work, requeue this one and try again
4563 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004564 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004565 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004566 synchronized (mQueueLock) {
4567 recordInitPendingLocked(true, transportName);
4568 }
4569 // do this via another alarm to make sure of the wakelock states
4570 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004571 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004572 + transportName + " resched in " + delay);
4573 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4574 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004575 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004576 }
4577 } catch (RemoteException e) {
4578 // can't happen; the transports are local
4579 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004580 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004581 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004582 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004583 mWakelock.release();
4584 }
4585 }
4586 }
4587
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004588 private void dataChangedImpl(String packageName) {
4589 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4590 dataChangedImpl(packageName, targets);
4591 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004592
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004593 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004594 // Record that we need a backup pass for the caller. Since multiple callers
4595 // may share a uid, we need to note all candidates within that uid and schedule
4596 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004597 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004598
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004599 if (targets == null) {
4600 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4601 + " uid=" + Binder.getCallingUid());
4602 return;
4603 }
4604
4605 synchronized (mQueueLock) {
4606 // Note that this client has made data changes that need to be backed up
4607 for (ApplicationInfo app : targets) {
4608 // validate the caller-supplied package name against the known set of
4609 // packages associated with this uid
4610 if (app.packageName.equals(packageName)) {
4611 // Add the caller to the set of pending backups. If there is
4612 // one already there, then overwrite it, but no harm done.
Christopher Tatecc55f812011-08-16 16:06:53 -07004613 BackupRequest req = new BackupRequest(packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08004614 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004615 // Journal this request in case of crash. The put()
4616 // operation returned null when this package was not already
4617 // in the set; we want to avoid touching the disk redundantly.
4618 writeToJournalLocked(packageName);
4619
Christopher Tatec58efa62011-08-01 19:20:14 -07004620 if (MORE_DEBUG) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004621 int numKeys = mPendingBackups.size();
4622 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4623 for (BackupRequest b : mPendingBackups.values()) {
Christopher Tatecc55f812011-08-16 16:06:53 -07004624 Slog.d(TAG, " + " + b);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004625 }
4626 }
4627 }
4628 }
4629 }
4630 }
4631 }
4632
4633 // Note: packageName is currently unused, but may be in the future
4634 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004635 // If the caller does not hold the BACKUP permission, it can only request a
4636 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004637 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004638 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004639 synchronized (mBackupParticipants) {
4640 return mBackupParticipants.get(Binder.getCallingUid());
4641 }
4642 }
4643
4644 // a caller with full permission can ask to back up any participating app
4645 // !!! TODO: allow backup of ANY app?
4646 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4647 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004648 int N = mBackupParticipants.size();
4649 for (int i = 0; i < N; i++) {
4650 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4651 if (s != null) {
4652 targets.addAll(s);
4653 }
4654 }
4655 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004656 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004657 }
Christopher Tate46758122009-05-06 11:22:00 -07004658
Christopher Tatecde87f42009-06-12 12:55:53 -07004659 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004660 RandomAccessFile out = null;
4661 try {
4662 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4663 out = new RandomAccessFile(mJournal, "rws");
4664 out.seek(out.length());
4665 out.writeUTF(str);
4666 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004667 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004668 mJournal = null;
4669 } finally {
4670 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004671 }
4672 }
4673
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004674 // ----- IBackupManager binder interface -----
4675
4676 public void dataChanged(final String packageName) {
4677 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4678 if (targets == null) {
4679 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4680 + " uid=" + Binder.getCallingUid());
4681 return;
4682 }
4683
4684 mBackupHandler.post(new Runnable() {
4685 public void run() {
4686 dataChangedImpl(packageName, targets);
4687 }
4688 });
4689 }
4690
Christopher Tateee0e78a2009-07-02 11:17:03 -07004691 // Clear the given package's backup data from the current transport
4692 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004693 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004694 PackageInfo info;
4695 try {
4696 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4697 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004698 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004699 return;
4700 }
4701
4702 // If the caller does not hold the BACKUP permission, it can only request a
4703 // wipe of its own backed-up data.
4704 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004705 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004706 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4707 apps = mBackupParticipants.get(Binder.getCallingUid());
4708 } else {
4709 // a caller with full permission can ask to back up any participating app
4710 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004711 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004712 apps = new HashSet<ApplicationInfo>();
4713 int N = mBackupParticipants.size();
4714 for (int i = 0; i < N; i++) {
4715 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4716 if (s != null) {
4717 apps.addAll(s);
4718 }
4719 }
4720 }
4721
4722 // now find the given package in the set of candidate apps
4723 for (ApplicationInfo app : apps) {
4724 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004725 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004726 // found it; fire off the clear request
4727 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004728 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004729 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004730 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4731 new ClearParams(getTransport(mCurrentTransport), info));
4732 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004733 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004734 }
4735 break;
4736 }
4737 }
4738 }
4739
Christopher Tateace7f092009-06-15 18:07:25 -07004740 // Run a backup pass immediately for any applications that have declared
4741 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004742 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004743 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004744
Joe Onorato8a9b2202010-02-26 18:56:32 -08004745 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004746 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004747 // Because the alarms we are using can jitter, and we want an *immediate*
4748 // backup pass to happen, we restart the timer beginning with "next time,"
4749 // then manually fire the backup trigger intent ourselves.
4750 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004751 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004752 mRunBackupIntent.send();
4753 } catch (PendingIntent.CanceledException e) {
4754 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004755 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004756 }
Christopher Tate46758122009-05-06 11:22:00 -07004757 }
4758 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004759
Christopher Tate4a627c72011-04-01 14:43:32 -07004760 // Run a *full* backup pass for the given package, writing the resulting data stream
4761 // to the supplied file descriptor. This method is synchronous and does not return
4762 // to the caller until the backup has been completed.
4763 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4764 boolean doAllApps, String[] pkgList) {
4765 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4766
4767 // Validate
4768 if (!doAllApps) {
4769 if (!includeShared) {
4770 // If we're backing up shared data (sdcard or equivalent), then we can run
4771 // without any supplied app names. Otherwise, we'd be doing no work, so
4772 // report the error.
4773 if (pkgList == null || pkgList.length == 0) {
4774 throw new IllegalArgumentException(
4775 "Backup requested but neither shared nor any apps named");
4776 }
4777 }
4778 }
4779
4780 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4781 + " shared=" + includeShared + " all=" + doAllApps
4782 + " pkgs=" + pkgList);
4783
4784 long oldId = Binder.clearCallingIdentity();
4785 try {
4786 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4787 doAllApps, pkgList);
4788 final int token = generateToken();
4789 synchronized (mFullConfirmations) {
4790 mFullConfirmations.put(token, params);
4791 }
4792
Christopher Tate75a99702011-05-18 16:28:19 -07004793 // start up the confirmation UI
4794 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4795 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4796 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004797 mFullConfirmations.delete(token);
4798 return;
4799 }
Christopher Tate75a99702011-05-18 16:28:19 -07004800
4801 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004802 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4803
4804 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004805 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004806
4807 // wait for the backup to be performed
4808 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4809 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004810 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004811 try {
4812 fd.close();
4813 } catch (IOException e) {
4814 // just eat it
4815 }
Christopher Tate75a99702011-05-18 16:28:19 -07004816 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07004817 }
Christopher Tatec58efa62011-08-01 19:20:14 -07004818 if (MORE_DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
Christopher Tate75a99702011-05-18 16:28:19 -07004819 }
4820
4821 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004822 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004823 Slog.i(TAG, "Beginning full restore...");
4824
4825 long oldId = Binder.clearCallingIdentity();
4826
4827 try {
4828 FullRestoreParams params = new FullRestoreParams(fd);
4829 final int token = generateToken();
4830 synchronized (mFullConfirmations) {
4831 mFullConfirmations.put(token, params);
4832 }
4833
4834 // start up the confirmation UI
4835 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4836 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4837 Slog.e(TAG, "Unable to launch full restore confirmation");
4838 mFullConfirmations.delete(token);
4839 return;
4840 }
4841
4842 // make sure the screen is lit for the user interaction
4843 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4844
4845 // start the confirmation countdown
4846 startConfirmationTimeout(token, params);
4847
4848 // wait for the restore to be performed
4849 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4850 waitForCompletion(params);
4851 } finally {
4852 try {
4853 fd.close();
4854 } catch (IOException e) {
4855 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4856 }
4857 Binder.restoreCallingIdentity(oldId);
4858 Slog.i(TAG, "Full restore completed");
4859 }
4860 }
4861
4862 boolean startConfirmationUi(int token, String action) {
4863 try {
4864 Intent confIntent = new Intent(action);
4865 confIntent.setClassName("com.android.backupconfirm",
4866 "com.android.backupconfirm.BackupRestoreConfirmation");
4867 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4868 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4869 mContext.startActivity(confIntent);
4870 } catch (ActivityNotFoundException e) {
4871 return false;
4872 }
4873 return true;
4874 }
4875
4876 void startConfirmationTimeout(int token, FullParams params) {
Christopher Tatec58efa62011-08-01 19:20:14 -07004877 if (MORE_DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
Christopher Tate75a99702011-05-18 16:28:19 -07004878 + TIMEOUT_FULL_CONFIRMATION + " millis");
4879 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4880 token, 0, params);
4881 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004882 }
4883
4884 void waitForCompletion(FullParams params) {
4885 synchronized (params.latch) {
4886 while (params.latch.get() == false) {
4887 try {
4888 params.latch.wait();
4889 } catch (InterruptedException e) { /* never interrupted */ }
4890 }
4891 }
4892 }
4893
4894 void signalFullBackupRestoreCompletion(FullParams params) {
4895 synchronized (params.latch) {
4896 params.latch.set(true);
4897 params.latch.notifyAll();
4898 }
4899 }
4900
4901 // Confirm that the previously-requested full backup/restore operation can proceed. This
4902 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004903 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004904 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004905 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004906 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4907 + " allow=" + allow);
4908
4909 // TODO: possibly require not just this signature-only permission, but even
4910 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004911 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004912
4913 long oldId = Binder.clearCallingIdentity();
4914 try {
4915
4916 FullParams params;
4917 synchronized (mFullConfirmations) {
4918 params = mFullConfirmations.get(token);
4919 if (params != null) {
4920 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4921 mFullConfirmations.delete(token);
4922
4923 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004924 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004925 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004926 : MSG_RUN_FULL_RESTORE;
4927
Christopher Tate728a1c42011-07-28 18:03:03 -07004928 params.observer = observer;
4929 params.curPassword = curPassword;
4930 params.encryptPassword = encPpassword;
4931
Christopher Tate75a99702011-05-18 16:28:19 -07004932 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004933 mWakelock.acquire();
4934 Message msg = mBackupHandler.obtainMessage(verb, params);
4935 mBackupHandler.sendMessage(msg);
4936 } else {
4937 Slog.w(TAG, "User rejected full backup/restore operation");
4938 // indicate completion without having actually transferred any data
4939 signalFullBackupRestoreCompletion(params);
4940 }
4941 } else {
4942 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4943 }
4944 }
4945 } finally {
4946 Binder.restoreCallingIdentity(oldId);
4947 }
4948 }
4949
Christopher Tate8031a3d2009-07-06 16:36:05 -07004950 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004951 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004952 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004953 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004954
Joe Onorato8a9b2202010-02-26 18:56:32 -08004955 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004956
Christopher Tate6ef58a12009-06-29 14:56:28 -07004957 boolean wasEnabled = mEnabled;
4958 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004959 Settings.Secure.putInt(mContext.getContentResolver(),
4960 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004961 mEnabled = enable;
4962 }
4963
Christopher Tate49401dd2009-07-01 12:34:29 -07004964 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004965 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004966 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004967 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004968 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004969 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004970 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004971
Christopher Tateb6787f22009-07-02 17:40:45 -07004972 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004973
4974 // This also constitutes an opt-out, so we wipe any data for
4975 // this device from the backend. We start that process with
4976 // an alarm in order to guarantee wakelock states.
4977 if (wasEnabled && mProvisioned) {
4978 // NOTE: we currently flush every registered transport, not just
4979 // the currently-active one.
4980 HashSet<String> allTransports;
4981 synchronized (mTransports) {
4982 allTransports = new HashSet<String>(mTransports.keySet());
4983 }
4984 // build the set of transports for which we are posting an init
4985 for (String transport : allTransports) {
4986 recordInitPendingLocked(true, transport);
4987 }
4988 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4989 mRunInitIntent);
4990 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004991 }
4992 }
Christopher Tate49401dd2009-07-01 12:34:29 -07004993 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004994
Christopher Tatecce9da52010-02-03 15:11:15 -08004995 // Enable/disable automatic restore of app data at install time
4996 public void setAutoRestore(boolean doAutoRestore) {
4997 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004998 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08004999
Joe Onorato8a9b2202010-02-26 18:56:32 -08005000 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08005001
5002 synchronized (this) {
5003 Settings.Secure.putInt(mContext.getContentResolver(),
5004 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
5005 mAutoRestore = doAutoRestore;
5006 }
5007 }
5008
Christopher Tate8031a3d2009-07-06 16:36:05 -07005009 // Mark the backup service as having been provisioned
5010 public void setBackupProvisioned(boolean available) {
5011 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5012 "setBackupProvisioned");
5013
5014 boolean wasProvisioned = mProvisioned;
5015 synchronized (this) {
5016 Settings.Secure.putInt(mContext.getContentResolver(),
5017 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
5018 mProvisioned = available;
5019 }
5020
5021 synchronized (mQueueLock) {
5022 if (available && !wasProvisioned && mEnabled) {
5023 // we're now good to go, so start the backup alarms
5024 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
5025 } else if (!available) {
5026 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08005027 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07005028 mAlarmManager.cancel(mRunBackupIntent);
5029 }
5030 }
5031 }
5032
5033 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07005034 // We used to use setInexactRepeating(), but that may be linked to
5035 // backups running at :00 more often than not, creating load spikes.
5036 // Schedule at an exact time for now, and also add a bit of "fuzz".
5037
5038 Random random = new Random();
5039 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
5040 random.nextInt(FUZZ_MILLIS);
5041 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
5042 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07005043 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07005044 }
5045
Christopher Tate6ef58a12009-06-29 14:56:28 -07005046 // Report whether the backup mechanism is currently enabled
5047 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04005048 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07005049 return mEnabled; // no need to synchronize just to read it
5050 }
5051
Christopher Tate91717492009-06-26 21:07:13 -07005052 // Report the name of the currently active transport
5053 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04005054 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07005055 "getCurrentTransport");
Christopher Tatec58efa62011-08-01 19:20:14 -07005056 if (MORE_DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07005057 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07005058 }
5059
Christopher Tate91717492009-06-26 21:07:13 -07005060 // Report all known, available backup transports
5061 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07005062 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07005063
Christopher Tate91717492009-06-26 21:07:13 -07005064 String[] list = null;
5065 ArrayList<String> known = new ArrayList<String>();
5066 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
5067 if (entry.getValue() != null) {
5068 known.add(entry.getKey());
5069 }
5070 }
5071
5072 if (known.size() > 0) {
5073 list = new String[known.size()];
5074 known.toArray(list);
5075 }
5076 return list;
5077 }
5078
5079 // Select which transport to use for the next backup operation. If the given
5080 // name is not one of the available transports, no action is taken and the method
5081 // returns null.
5082 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04005083 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07005084
5085 synchronized (mTransports) {
5086 String prevTransport = null;
5087 if (mTransports.get(transport) != null) {
5088 prevTransport = mCurrentTransport;
5089 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07005090 Settings.Secure.putString(mContext.getContentResolver(),
5091 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005092 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07005093 + " returning " + prevTransport);
5094 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005095 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07005096 }
5097 return prevTransport;
5098 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005099 }
5100
Christopher Tatef5e1c292010-12-08 18:40:26 -08005101 // Supply the configuration Intent for the given transport. If the name is not one
5102 // of the available transports, or if the transport does not supply any configuration
5103 // UI, the method returns null.
5104 public Intent getConfigurationIntent(String transportName) {
5105 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5106 "getConfigurationIntent");
5107
5108 synchronized (mTransports) {
5109 final IBackupTransport transport = mTransports.get(transportName);
5110 if (transport != null) {
5111 try {
5112 final Intent intent = transport.configurationIntent();
Christopher Tatec58efa62011-08-01 19:20:14 -07005113 if (MORE_DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
Christopher Tatef5e1c292010-12-08 18:40:26 -08005114 + intent);
5115 return intent;
5116 } catch (RemoteException e) {
5117 /* fall through to return null */
5118 }
5119 }
5120 }
5121
5122 return null;
5123 }
5124
5125 // Supply the configuration summary string for the given transport. If the name is
5126 // not one of the available transports, or if the transport does not supply any
5127 // summary / destination string, the method can return null.
5128 //
5129 // This string is used VERBATIM as the summary text of the relevant Settings item!
5130 public String getDestinationString(String transportName) {
5131 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07005132 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08005133
5134 synchronized (mTransports) {
5135 final IBackupTransport transport = mTransports.get(transportName);
5136 if (transport != null) {
5137 try {
5138 final String text = transport.currentDestinationString();
Christopher Tatec58efa62011-08-01 19:20:14 -07005139 if (MORE_DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
Christopher Tatef5e1c292010-12-08 18:40:26 -08005140 return text;
5141 } catch (RemoteException e) {
5142 /* fall through to return null */
5143 }
5144 }
5145 }
5146
5147 return null;
5148 }
5149
Christopher Tate043dadc2009-06-02 16:11:00 -07005150 // Callback: a requested backup agent has been instantiated. This should only
5151 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005152 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07005153 synchronized(mAgentConnectLock) {
5154 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005155 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07005156 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
5157 mConnectedAgent = agent;
5158 mConnecting = false;
5159 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005160 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005161 + " claiming agent connected");
5162 }
5163 mAgentConnectLock.notifyAll();
5164 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005165 }
5166
5167 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
5168 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07005169 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07005170 public void agentDisconnected(String packageName) {
5171 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07005172 synchronized(mAgentConnectLock) {
5173 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
5174 mConnectedAgent = null;
5175 mConnecting = false;
5176 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005177 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07005178 + " claiming agent disconnected");
5179 }
5180 mAgentConnectLock.notifyAll();
5181 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005182 }
Christopher Tate181fafa2009-05-14 11:12:14 -07005183
Christopher Tate1bb69062010-02-19 17:02:12 -08005184 // An application being installed will need a restore pass, then the Package Manager
5185 // will need to be told when the restore is finished.
5186 public void restoreAtInstall(String packageName, int token) {
5187 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005188 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08005189 + " attemping install-time restore");
5190 return;
5191 }
5192
5193 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005194 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08005195 + " token=" + Integer.toHexString(token));
5196
Christopher Tatef0872722010-02-25 15:22:48 -08005197 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08005198 // okay, we're going to attempt a restore of this package from this restore set.
5199 // The eventual message back into the Package Manager to run the post-install
5200 // steps for 'token' will be issued from the restore handling code.
5201
5202 // We can use a synthetic PackageInfo here because:
5203 // 1. We know it's valid, since the Package Manager supplied the name
5204 // 2. Only the packageName field will be used by the restore code
5205 PackageInfo pkg = new PackageInfo();
5206 pkg.packageName = packageName;
5207
5208 mWakelock.acquire();
5209 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5210 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07005211 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08005212 mBackupHandler.sendMessage(msg);
5213 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08005214 // Auto-restore disabled or no way to attempt a restore; just tell the Package
5215 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005216 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08005217 try {
5218 mPackageManagerBinder.finishPackageInstall(token);
5219 } catch (RemoteException e) { /* can't happen */ }
5220 }
5221 }
5222
Christopher Tate8c850b72009-06-07 19:33:20 -07005223 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08005224 public IRestoreSession beginRestoreSession(String packageName, String transport) {
5225 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
5226 + " transport=" + transport);
5227
5228 boolean needPermission = true;
5229 if (transport == null) {
5230 transport = mCurrentTransport;
5231
5232 if (packageName != null) {
5233 PackageInfo app = null;
5234 try {
5235 app = mPackageManager.getPackageInfo(packageName, 0);
5236 } catch (NameNotFoundException nnf) {
5237 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
5238 throw new IllegalArgumentException("Package " + packageName + " not found");
5239 }
5240
5241 if (app.applicationInfo.uid == Binder.getCallingUid()) {
5242 // So: using the current active transport, and the caller has asked
5243 // that its own package will be restored. In this narrow use case
5244 // we do not require the caller to hold the permission.
5245 needPermission = false;
5246 }
5247 }
5248 }
5249
5250 if (needPermission) {
5251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5252 "beginRestoreSession");
5253 } else {
5254 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
5255 }
Christopher Tatef68eb502009-06-16 11:02:01 -07005256
5257 synchronized(this) {
5258 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005259 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07005260 return null;
5261 }
Chris Tate44ab8452010-11-16 15:10:49 -08005262 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08005263 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07005264 }
5265 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07005266 }
Christopher Tate043dadc2009-06-02 16:11:00 -07005267
Christopher Tate73a3cb32010-12-13 18:27:26 -08005268 void clearRestoreSession(ActiveRestoreSession currentSession) {
5269 synchronized(this) {
5270 if (currentSession != mActiveRestoreSession) {
5271 Slog.e(TAG, "ending non-current restore session");
5272 } else {
5273 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
5274 mActiveRestoreSession = null;
5275 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
5276 }
5277 }
5278 }
5279
Christopher Tate44a27902010-01-27 17:15:49 -08005280 // Note that a currently-active backup agent has notified us that it has
5281 // completed the given outstanding asynchronous backup/restore operation.
Christopher Tate8e294d42011-08-31 20:37:12 -07005282 @Override
Christopher Tate44a27902010-01-27 17:15:49 -08005283 public void opComplete(int token) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005284 if (MORE_DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
5285 Operation op = null;
Christopher Tate44a27902010-01-27 17:15:49 -08005286 synchronized (mCurrentOpLock) {
Christopher Tate8e294d42011-08-31 20:37:12 -07005287 op = mCurrentOperations.get(token);
5288 if (op != null) {
5289 op.state = OP_ACKNOWLEDGED;
5290 }
Christopher Tate44a27902010-01-27 17:15:49 -08005291 mCurrentOpLock.notifyAll();
5292 }
Christopher Tate8e294d42011-08-31 20:37:12 -07005293
5294 // The completion callback, if any, is invoked on the handler
5295 if (op != null && op.callback != null) {
5296 Message msg = mBackupHandler.obtainMessage(MSG_OP_COMPLETE, op.callback);
5297 mBackupHandler.sendMessage(msg);
5298 }
Christopher Tate44a27902010-01-27 17:15:49 -08005299 }
5300
Christopher Tate9b3905c2009-06-08 15:24:01 -07005301 // ----- Restore session -----
5302
Christopher Tate80202c82010-01-25 19:37:47 -08005303 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07005304 private static final String TAG = "RestoreSession";
5305
Chris Tate44ab8452010-11-16 15:10:49 -08005306 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005307 private IBackupTransport mRestoreTransport = null;
5308 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08005309 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07005310
Chris Tate44ab8452010-11-16 15:10:49 -08005311 ActiveRestoreSession(String packageName, String transport) {
5312 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07005313 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07005314 }
5315
5316 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07005317 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04005318 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005319 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005320 if (observer == null) {
5321 throw new IllegalArgumentException("Observer must not be null");
5322 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005323
Christopher Tate73a3cb32010-12-13 18:27:26 -08005324 if (mEnded) {
5325 throw new IllegalStateException("Restore session already ended");
5326 }
5327
Christopher Tate1bb69062010-02-19 17:02:12 -08005328 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07005329 try {
Christopher Tate43383042009-07-13 15:17:13 -07005330 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005331 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07005332 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07005333 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07005334 // spin off the transport request to our service thread
5335 mWakelock.acquire();
5336 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
5337 new RestoreGetSetsParams(mRestoreTransport, this, observer));
5338 mBackupHandler.sendMessage(msg);
5339 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07005340 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005341 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07005342 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08005343 } finally {
5344 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07005345 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07005346 }
5347
Christopher Tate84725812010-02-04 15:52:40 -08005348 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07005349 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5350 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005351
Chris Tate44ab8452010-11-16 15:10:49 -08005352 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07005353 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005354
Christopher Tate73a3cb32010-12-13 18:27:26 -08005355 if (mEnded) {
5356 throw new IllegalStateException("Restore session already ended");
5357 }
5358
Dan Egnor0084da52009-07-29 12:57:16 -07005359 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08005360 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5361 return -1;
5362 }
5363
5364 if (mPackageName != null) {
5365 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07005366 return -1;
5367 }
5368
Christopher Tate21ab6a52009-09-24 18:01:46 -07005369 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07005370 for (int i = 0; i < mRestoreSets.length; i++) {
5371 if (token == mRestoreSets[i].token) {
5372 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07005373 mWakelock.acquire();
5374 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005375 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07005376 mBackupHandler.sendMessage(msg);
5377 Binder.restoreCallingIdentity(oldId);
5378 return 0;
5379 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07005380 }
5381 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07005382
Joe Onorato8a9b2202010-02-26 18:56:32 -08005383 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07005384 return -1;
5385 }
5386
Christopher Tate284f1bb2011-07-07 14:31:18 -07005387 public synchronized int restoreSome(long token, IRestoreObserver observer,
5388 String[] packages) {
5389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
5390 "performRestore");
5391
5392 if (DEBUG) {
5393 StringBuilder b = new StringBuilder(128);
5394 b.append("restoreSome token=");
5395 b.append(Long.toHexString(token));
5396 b.append(" observer=");
5397 b.append(observer.toString());
5398 b.append(" packages=");
5399 if (packages == null) {
5400 b.append("null");
5401 } else {
5402 b.append('{');
5403 boolean first = true;
5404 for (String s : packages) {
5405 if (!first) {
5406 b.append(", ");
5407 } else first = false;
5408 b.append(s);
5409 }
5410 b.append('}');
5411 }
5412 Slog.d(TAG, b.toString());
5413 }
5414
5415 if (mEnded) {
5416 throw new IllegalStateException("Restore session already ended");
5417 }
5418
5419 if (mRestoreTransport == null || mRestoreSets == null) {
5420 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
5421 return -1;
5422 }
5423
5424 if (mPackageName != null) {
5425 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
5426 return -1;
5427 }
5428
5429 synchronized (mQueueLock) {
5430 for (int i = 0; i < mRestoreSets.length; i++) {
5431 if (token == mRestoreSets[i].token) {
5432 long oldId = Binder.clearCallingIdentity();
5433 mWakelock.acquire();
5434 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
5435 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
5436 packages, true);
5437 mBackupHandler.sendMessage(msg);
5438 Binder.restoreCallingIdentity(oldId);
5439 return 0;
5440 }
5441 }
5442 }
5443
5444 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5445 return -1;
5446 }
5447
Christopher Tate84725812010-02-04 15:52:40 -08005448 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005449 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005450
Christopher Tate73a3cb32010-12-13 18:27:26 -08005451 if (mEnded) {
5452 throw new IllegalStateException("Restore session already ended");
5453 }
5454
Chris Tate44ab8452010-11-16 15:10:49 -08005455 if (mPackageName != null) {
5456 if (! mPackageName.equals(packageName)) {
5457 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5458 + " on session for package " + mPackageName);
5459 return -1;
5460 }
5461 }
5462
Christopher Tate84725812010-02-04 15:52:40 -08005463 PackageInfo app = null;
5464 try {
5465 app = mPackageManager.getPackageInfo(packageName, 0);
5466 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005467 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005468 return -1;
5469 }
5470
5471 // If the caller is not privileged and is not coming from the target
5472 // app's uid, throw a permission exception back to the caller.
5473 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5474 Binder.getCallingPid(), Binder.getCallingUid());
5475 if ((perm == PackageManager.PERMISSION_DENIED) &&
5476 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005477 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005478 + " or calling uid=" + Binder.getCallingUid());
5479 throw new SecurityException("No permission to restore other packages");
5480 }
5481
Christopher Tate7d411a32010-02-26 11:27:08 -08005482 // If the package has no backup agent, we obviously cannot proceed
5483 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005484 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005485 return -1;
5486 }
5487
Christopher Tate84725812010-02-04 15:52:40 -08005488 // So far so good; we're allowed to try to restore this package. Now
5489 // check whether there is data for it in the current dataset, falling back
5490 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005491 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005492
5493 // If we didn't come up with a place to look -- no ancestral dataset and
5494 // the app has never been backed up from this device -- there's nothing
5495 // to do but return failure.
5496 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005497 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005498 return -1;
5499 }
5500
5501 // Ready to go: enqueue the restore request and claim success
5502 long oldId = Binder.clearCallingIdentity();
5503 mWakelock.acquire();
5504 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005505 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005506 mBackupHandler.sendMessage(msg);
5507 Binder.restoreCallingIdentity(oldId);
5508 return 0;
5509 }
5510
Christopher Tate73a3cb32010-12-13 18:27:26 -08005511 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5512 class EndRestoreRunnable implements Runnable {
5513 BackupManagerService mBackupManager;
5514 ActiveRestoreSession mSession;
5515
5516 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5517 mBackupManager = manager;
5518 mSession = session;
5519 }
5520
5521 public void run() {
5522 // clean up the session's bookkeeping
5523 synchronized (mSession) {
5524 try {
5525 if (mSession.mRestoreTransport != null) {
5526 mSession.mRestoreTransport.finishRestore();
5527 }
5528 } catch (Exception e) {
5529 Slog.e(TAG, "Error in finishRestore", e);
5530 } finally {
5531 mSession.mRestoreTransport = null;
5532 mSession.mEnded = true;
5533 }
5534 }
5535
5536 // clean up the BackupManagerService side of the bookkeeping
5537 // and cancel any pending timeout message
5538 mBackupManager.clearRestoreSession(mSession);
5539 }
5540 }
5541
Dan Egnor0084da52009-07-29 12:57:16 -07005542 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005543 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005544
Christopher Tate73a3cb32010-12-13 18:27:26 -08005545 if (mEnded) {
5546 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005547 }
5548
Christopher Tate73a3cb32010-12-13 18:27:26 -08005549 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005550 }
5551 }
5552
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005553 @Override
5554 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005555 long identityToken = Binder.clearCallingIdentity();
5556 try {
5557 dumpInternal(pw);
5558 } finally {
5559 Binder.restoreCallingIdentity(identityToken);
5560 }
5561 }
5562
5563 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005564 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005565 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005566 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005567 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005568 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005569 pw.println("Last backup pass: " + mLastBackupPass
5570 + " (now = " + System.currentTimeMillis() + ')');
5571 pw.println(" next scheduled: " + mNextBackupPass);
5572
Christopher Tate91717492009-06-26 21:07:13 -07005573 pw.println("Available transports:");
5574 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005575 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5576 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005577 IBackupTransport transport = getTransport(t);
5578 File dir = new File(mBaseStateDir, transport.transportDirName());
5579 pw.println(" destination: " + transport.currentDestinationString());
5580 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005581 for (File f : dir.listFiles()) {
5582 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5583 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005584 } catch (Exception e) {
5585 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005586 pw.println(" Error: " + e);
5587 }
Christopher Tate91717492009-06-26 21:07:13 -07005588 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005589
5590 pw.println("Pending init: " + mPendingInits.size());
5591 for (String s : mPendingInits) {
5592 pw.println(" " + s);
5593 }
5594
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005595 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005596 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005597 for (int i=0; i<N; i++) {
5598 int uid = mBackupParticipants.keyAt(i);
5599 pw.print(" uid: ");
5600 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005601 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5602 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005603 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005604 }
5605 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005606
Christopher Tateb49ceb32010-02-08 16:22:24 -08005607 pw.println("Ancestral packages: "
5608 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005609 if (mAncestralPackages != null) {
5610 for (String pkg : mAncestralPackages) {
5611 pw.println(" " + pkg);
5612 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005613 }
5614
Christopher Tate73e02522009-07-15 14:18:26 -07005615 pw.println("Ever backed up: " + mEverStoredApps.size());
5616 for (String pkg : mEverStoredApps) {
5617 pw.println(" " + pkg);
5618 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005619
5620 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005621 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005622 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005623 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005624 }
5625 }
Christopher Tate487529a2009-04-29 14:03:25 -07005626}