blob: 3ec2a9675bb40b4598c868050968e8e6830d0eef [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;
132
133 // Name and current contents version of the full-backup manifest file
134 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
135 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700136 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
137 static final int BACKUP_FILE_VERSION = 1;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700138 static final boolean COMPRESS_FULL_BACKUPS = true; // should be true in production
Christopher Tateaa088442009-06-16 18:25:46 -0700139
Christopher Tate49401dd2009-07-01 12:34:29 -0700140 // How often we perform a backup pass. Privileged external callers can
141 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700142 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700143
Dan Egnorc1c49c02009-10-30 17:35:39 -0700144 // Random variation in backup scheduling time to avoid server load spikes
145 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
146
Christopher Tate8031a3d2009-07-06 16:36:05 -0700147 // The amount of time between the initial provisioning of the device and
148 // the first backup pass.
149 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
150
Christopher Tate45281862010-03-05 15:46:30 -0800151 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
152 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
153 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700154 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700155 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700156 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700157 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700158 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700159 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
160 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800161 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700162 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
163 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700164
165 // Timeout interval for deciding that a bind or clear-data has taken too long
166 static final long TIMEOUT_INTERVAL = 10 * 1000;
167
Christopher Tate44a27902010-01-27 17:15:49 -0800168 // Timeout intervals for agent backup & restore operations
169 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700170 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700171 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800172 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
173
Christopher Tate2efd2db2011-07-19 16:32:49 -0700174 // User confirmation timeout for a full backup/restore operation. It's this long in
175 // order to give them time to enter the backup password.
176 static final long TIMEOUT_FULL_CONFIRMATION = 60 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700177
Christopher Tate487529a2009-04-29 14:03:25 -0700178 private Context mContext;
179 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800180 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700181 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700182 private PowerManager mPowerManager;
183 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800184 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700185
Christopher Tate73e02522009-07-15 14:18:26 -0700186 boolean mEnabled; // access to this is synchronized on 'this'
187 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800188 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700189 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800190 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
191 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700192 PendingIntent mRunBackupIntent, mRunInitIntent;
193 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700194 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700195 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700196 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700197 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700198 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700199 public ApplicationInfo appInfo;
Christopher Tateaa088442009-06-16 18:25:46 -0700200
Christopher Tate4a627c72011-04-01 14:43:32 -0700201 BackupRequest(ApplicationInfo app) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700202 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700203 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700204
205 public String toString() {
Christopher Tate4a627c72011-04-01 14:43:32 -0700206 return "BackupRequest{app=" + appInfo + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700207 }
Christopher Tate46758122009-05-06 11:22:00 -0700208 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800209 // Backups that we haven't started yet. Keys are package names.
210 HashMap<String,BackupRequest> mPendingBackups
211 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700212
213 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700214 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700215
216 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700217 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700218
Christopher Tate043dadc2009-06-02 16:11:00 -0700219 // The thread performing the sequence of queued backups binds to each app's agent
220 // in succession. Bind notifications are asynchronously delivered through the
221 // Activity Manager; use this lock object to signal when a requested binding has
222 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700223 final Object mAgentConnectLock = new Object();
224 IBackupAgent mConnectedAgent;
225 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700226 volatile long mLastBackupPass;
227 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700228
Christopher Tate55f931a2009-09-29 17:17:34 -0700229 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700230 final Object mClearDataLock = new Object();
231 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700232
Christopher Tate91717492009-06-26 21:07:13 -0700233 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700234 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700235 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700236 String mCurrentTransport;
237 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800238 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700239
Christopher Tate2d449afe2010-03-29 19:14:24 -0700240 class RestoreGetSetsParams {
241 public IBackupTransport transport;
242 public ActiveRestoreSession session;
243 public IRestoreObserver observer;
244
245 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
246 IRestoreObserver _observer) {
247 transport = _transport;
248 session = _session;
249 observer = _observer;
250 }
251 }
252
Christopher Tate73e02522009-07-15 14:18:26 -0700253 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700254 public IBackupTransport transport;
255 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700256 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800257 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800258 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700259 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700260 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800261
262 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700263 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800264 transport = _transport;
265 observer = _obs;
266 token = _token;
267 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800268 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700269 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700270 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800271 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700272
Chris Tate249345b2010-10-29 12:57:04 -0700273 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
274 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700275 transport = _transport;
276 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700277 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800278 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800279 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700280 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700281 filterSet = null;
282 }
283
284 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
285 String[] _filterSet, boolean _needFullBackup) {
286 transport = _transport;
287 observer = _obs;
288 token = _token;
289 pkgInfo = null;
290 pmToken = 0;
291 needFullBackup = _needFullBackup;
292 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700293 }
294 }
295
Christopher Tate73e02522009-07-15 14:18:26 -0700296 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700297 public IBackupTransport transport;
298 public PackageInfo packageInfo;
299
300 ClearParams(IBackupTransport _transport, PackageInfo _info) {
301 transport = _transport;
302 packageInfo = _info;
303 }
304 }
305
Christopher Tate4a627c72011-04-01 14:43:32 -0700306 class FullParams {
307 public ParcelFileDescriptor fd;
308 public final AtomicBoolean latch;
309 public IFullBackupRestoreObserver observer;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700310 public String password; // filled in by the confirmation step
Christopher Tate4a627c72011-04-01 14:43:32 -0700311
312 FullParams() {
313 latch = new AtomicBoolean(false);
314 }
315 }
316
317 class FullBackupParams extends FullParams {
318 public boolean includeApks;
319 public boolean includeShared;
320 public boolean allApps;
321 public String[] packages;
322
323 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
324 boolean doAllApps, String[] pkgList) {
325 fd = output;
326 includeApks = saveApks;
327 includeShared = saveShared;
328 allApps = doAllApps;
329 packages = pkgList;
330 }
331 }
332
333 class FullRestoreParams extends FullParams {
334 FullRestoreParams(ParcelFileDescriptor input) {
335 fd = input;
336 }
337 }
338
Christopher Tate44a27902010-01-27 17:15:49 -0800339 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
340 // token is the index of the entry in the pending-operations list.
341 static final int OP_PENDING = 0;
342 static final int OP_ACKNOWLEDGED = 1;
343 static final int OP_TIMEOUT = -1;
344
345 final SparseIntArray mCurrentOperations = new SparseIntArray();
346 final Object mCurrentOpLock = new Object();
347 final Random mTokenGenerator = new Random();
348
Christopher Tate4a627c72011-04-01 14:43:32 -0700349 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
350
Christopher Tate5cb400b2009-06-25 16:03:14 -0700351 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700352 File mBaseStateDir;
353 File mDataDir;
354 File mJournalDir;
355 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700356
Christopher Tate2efd2db2011-07-19 16:32:49 -0700357 // Backup password, if any, and the file where it's saved. What is stored is not the
358 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
359 // persisted) salt. Validation is performed by running the challenge text through the
360 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
361 // the saved hash string, then the challenge text matches the originally supplied
362 // password text.
363 private final SecureRandom mRng = new SecureRandom();
364 private String mPasswordHash;
365 private File mPasswordHashFile;
366 private byte[] mPasswordSalt;
367
368 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
369 static final int PBKDF2_HASH_ROUNDS = 10000;
370 static final int PBKDF2_KEY_SIZE = 256; // bits
371 static final int PBKDF2_SALT_SIZE = 512; // bits
372 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
373
Christopher Tate84725812010-02-04 15:52:40 -0800374 // Keep a log of all the apps we've ever backed up, and what the
375 // dataset tokens are for both the current backup dataset and
376 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700377 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700378 HashSet<String> mEverStoredApps = new HashSet<String>();
379
Christopher Tateb49ceb32010-02-08 16:22:24 -0800380 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800381 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800382 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800383 long mAncestralToken = 0;
384 long mCurrentToken = 0;
385
Christopher Tate4cc86e12009-09-21 19:36:51 -0700386 // Persistently track the need to do a full init
387 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
388 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700389
Christopher Tate4a627c72011-04-01 14:43:32 -0700390 // Utility: build a new random integer token
391 int generateToken() {
392 int token;
393 do {
394 synchronized (mTokenGenerator) {
395 token = mTokenGenerator.nextInt();
396 }
397 } while (token < 0);
398 return token;
399 }
400
Christopher Tate44a27902010-01-27 17:15:49 -0800401 // ----- Asynchronous backup/restore handler thread -----
402
403 private class BackupHandler extends Handler {
404 public BackupHandler(Looper looper) {
405 super(looper);
406 }
407
408 public void handleMessage(Message msg) {
409
410 switch (msg.what) {
411 case MSG_RUN_BACKUP:
412 {
413 mLastBackupPass = System.currentTimeMillis();
414 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
415
416 IBackupTransport transport = getTransport(mCurrentTransport);
417 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800418 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800419 mWakelock.release();
420 break;
421 }
422
423 // snapshot the pending-backup set and work on that
424 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800425 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800426 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800427 // Do we have any work to do? Construct the work queue
428 // then release the synchronization lock to actually run
429 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800430 if (mPendingBackups.size() > 0) {
431 for (BackupRequest b: mPendingBackups.values()) {
432 queue.add(b);
433 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800434 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800435 mPendingBackups.clear();
436
437 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800438 mJournal = null;
439
Christopher Tate44a27902010-01-27 17:15:49 -0800440 }
441 }
Christopher Tatec61da312010-02-05 10:41:27 -0800442
443 if (queue.size() > 0) {
444 // At this point, we have started a new journal file, and the old
445 // file identity is being passed to the backup processing thread.
446 // When it completes successfully, that old journal file will be
447 // deleted. If we crash prior to that, the old journal is parsed
448 // at next boot and the journaled requests fulfilled.
449 (new PerformBackupTask(transport, queue, oldJournal)).run();
450 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800451 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800452 mWakelock.release();
453 }
Christopher Tate44a27902010-01-27 17:15:49 -0800454 break;
455 }
456
457 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700458 {
459 FullBackupParams params = (FullBackupParams)msg.obj;
460 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
Christopher Tate2efd2db2011-07-19 16:32:49 -0700461 params.includeShared, params.password, params.allApps, params.packages,
Christopher Tate4a627c72011-04-01 14:43:32 -0700462 params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800463 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700464 }
Christopher Tate44a27902010-01-27 17:15:49 -0800465
466 case MSG_RUN_RESTORE:
467 {
468 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800469 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800470 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700471 params.token, params.pkgInfo, params.pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -0700472 params.needFullBackup, params.filterSet)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800473 break;
474 }
475
Christopher Tate75a99702011-05-18 16:28:19 -0700476 case MSG_RUN_FULL_RESTORE:
477 {
478 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tate2efd2db2011-07-19 16:32:49 -0700479 (new PerformFullRestoreTask(params.fd, params.password,
480 params.observer, params.latch)).run();
Christopher Tate75a99702011-05-18 16:28:19 -0700481 break;
482 }
483
Christopher Tate44a27902010-01-27 17:15:49 -0800484 case MSG_RUN_CLEAR:
485 {
486 ClearParams params = (ClearParams)msg.obj;
487 (new PerformClearTask(params.transport, params.packageInfo)).run();
488 break;
489 }
490
491 case MSG_RUN_INITIALIZE:
492 {
493 HashSet<String> queue;
494
495 // Snapshot the pending-init queue and work on that
496 synchronized (mQueueLock) {
497 queue = new HashSet<String>(mPendingInits);
498 mPendingInits.clear();
499 }
500
501 (new PerformInitializeTask(queue)).run();
502 break;
503 }
504
Christopher Tate2d449afe2010-03-29 19:14:24 -0700505 case MSG_RUN_GET_RESTORE_SETS:
506 {
507 // Like other async operations, this is entered with the wakelock held
508 RestoreSet[] sets = null;
509 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
510 try {
511 sets = params.transport.getAvailableRestoreSets();
512 // cache the result in the active session
513 synchronized (params.session) {
514 params.session.mRestoreSets = sets;
515 }
516 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
517 } catch (Exception e) {
518 Slog.e(TAG, "Error from transport getting set list");
519 } finally {
520 if (params.observer != null) {
521 try {
522 params.observer.restoreSetsAvailable(sets);
523 } catch (RemoteException re) {
524 Slog.e(TAG, "Unable to report listing to observer");
525 } catch (Exception e) {
526 Slog.e(TAG, "Restore observer threw", e);
527 }
528 }
529
Christopher Tate2a935092011-03-03 17:30:32 -0800530 // Done: reset the session timeout clock
531 removeMessages(MSG_RESTORE_TIMEOUT);
532 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
533
Christopher Tate2d449afe2010-03-29 19:14:24 -0700534 mWakelock.release();
535 }
536 break;
537 }
538
Christopher Tate44a27902010-01-27 17:15:49 -0800539 case MSG_TIMEOUT:
540 {
541 synchronized (mCurrentOpLock) {
542 final int token = msg.arg1;
543 int state = mCurrentOperations.get(token, OP_TIMEOUT);
544 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800545 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800546 mCurrentOperations.put(token, OP_TIMEOUT);
547 }
548 mCurrentOpLock.notifyAll();
549 }
550 break;
551 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800552
553 case MSG_RESTORE_TIMEOUT:
554 {
555 synchronized (BackupManagerService.this) {
556 if (mActiveRestoreSession != null) {
557 // Client app left the restore session dangling. We know that it
558 // can't be in the middle of an actual restore operation because
559 // those are executed serially on this same handler thread. Clean
560 // up now.
561 Slog.w(TAG, "Restore session timed out; aborting");
562 post(mActiveRestoreSession.new EndRestoreRunnable(
563 BackupManagerService.this, mActiveRestoreSession));
564 }
565 }
566 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700567
568 case MSG_FULL_CONFIRMATION_TIMEOUT:
569 {
570 synchronized (mFullConfirmations) {
571 FullParams params = mFullConfirmations.get(msg.arg1);
572 if (params != null) {
573 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
574
575 // Release the waiter; timeout == completion
576 signalFullBackupRestoreCompletion(params);
577
578 // Remove the token from the set
579 mFullConfirmations.delete(msg.arg1);
580
581 // Report a timeout to the observer, if any
582 if (params.observer != null) {
583 try {
584 params.observer.onTimeout();
585 } catch (RemoteException e) {
586 /* don't care if the app has gone away */
587 }
588 }
589 } else {
590 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
591 }
592 }
593 break;
594 }
Christopher Tate44a27902010-01-27 17:15:49 -0800595 }
596 }
597 }
598
599 // ----- Main service implementation -----
600
Christopher Tate487529a2009-04-29 14:03:25 -0700601 public BackupManagerService(Context context) {
602 mContext = context;
603 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700604 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700605 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700606
Christopher Tateb6787f22009-07-02 17:40:45 -0700607 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
608 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
609
Christopher Tate44a27902010-01-27 17:15:49 -0800610 mBackupManagerBinder = asInterface(asBinder());
611
612 // spin up the backup/restore handler thread
613 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
614 mHandlerThread.start();
615 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
616
Christopher Tate22b87872009-05-04 16:41:53 -0700617 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700618 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700619 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700620 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700621 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800622 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800623 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800624 // If Encrypted file systems is enabled or disabled, this call will return the
625 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600626 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800627 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700628 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700629
Christopher Tate2efd2db2011-07-19 16:32:49 -0700630 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
631 if (mPasswordHashFile.exists()) {
632 FileInputStream fin = null;
633 DataInputStream in = null;
634 try {
635 fin = new FileInputStream(mPasswordHashFile);
636 in = new DataInputStream(new BufferedInputStream(fin));
637 // integer length of the salt array, followed by the salt,
638 // then the hex pw hash string
639 int saltLen = in.readInt();
640 byte[] salt = new byte[saltLen];
641 in.readFully(salt);
642 mPasswordHash = in.readUTF();
643 mPasswordSalt = salt;
644 } catch (IOException e) {
645 Slog.e(TAG, "Unable to read saved backup pw hash");
646 } finally {
647 try {
648 if (in != null) in.close();
649 if (fin != null) fin.close();
650 } catch (IOException e) {
651 Slog.w(TAG, "Unable to close streams");
652 }
653 }
654 }
655
Christopher Tate4cc86e12009-09-21 19:36:51 -0700656 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700657 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700658 IntentFilter filter = new IntentFilter();
659 filter.addAction(RUN_BACKUP_ACTION);
660 context.registerReceiver(mRunBackupReceiver, filter,
661 android.Manifest.permission.BACKUP, null);
662
663 mRunInitReceiver = new RunInitializeReceiver();
664 filter = new IntentFilter();
665 filter.addAction(RUN_INITIALIZE_ACTION);
666 context.registerReceiver(mRunInitReceiver, filter,
667 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700668
669 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700670 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
671 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
672
Christopher Tate4cc86e12009-09-21 19:36:51 -0700673 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
674 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
675 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
676
Christopher Tatecde87f42009-06-12 12:55:53 -0700677 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700678 mJournalDir = new File(mBaseStateDir, "pending");
679 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700680 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700681
Christopher Tate73e02522009-07-15 14:18:26 -0700682 // Set up the various sorts of package tracking we do
683 initPackageTracking();
684
Christopher Tateabce4e82009-06-18 18:35:32 -0700685 // Build our mapping of uid to backup client services. This implicitly
686 // schedules a backup pass on the Package Manager metadata the first
687 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700688 synchronized (mBackupParticipants) {
689 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700690 }
691
Dan Egnor87a02bc2009-06-17 02:30:10 -0700692 // Set up our transport options and initialize the default transport
693 // TODO: Have transports register themselves somehow?
694 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700695 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700696 ComponentName localName = new ComponentName(context, LocalTransport.class);
697 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700698
Christopher Tate91717492009-06-26 21:07:13 -0700699 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700700 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
701 Settings.Secure.BACKUP_TRANSPORT);
702 if ("".equals(mCurrentTransport)) {
703 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700704 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800705 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700706
707 // Attach to the Google backup transport. When this comes up, it will set
708 // itself as the current transport because we explicitly reset mCurrentTransport
709 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700710 ComponentName transportComponent = new ComponentName("com.google.android.backup",
711 "com.google.android.backup.BackupTransportService");
712 try {
713 // If there's something out there that is supposed to be the Google
714 // backup transport, make sure it's legitimately part of the OS build
715 // and not an app lying about its package name.
716 ApplicationInfo info = mPackageManager.getApplicationInfo(
717 transportComponent.getPackageName(), 0);
718 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
719 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
720 Intent intent = new Intent().setComponent(transportComponent);
721 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
722 } else {
723 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
724 }
725 } catch (PackageManager.NameNotFoundException nnf) {
726 // No such package? No binding.
727 if (DEBUG) Slog.v(TAG, "Google transport not present");
728 }
Christopher Tateaa088442009-06-16 18:25:46 -0700729
Christopher Tatecde87f42009-06-12 12:55:53 -0700730 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700731 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700732 parseLeftoverJournals();
733
Christopher Tateb6787f22009-07-02 17:40:45 -0700734 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700735 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700736
737 // Start the backup passes going
738 setBackupEnabled(areEnabled);
739 }
740
741 private class RunBackupReceiver extends BroadcastReceiver {
742 public void onReceive(Context context, Intent intent) {
743 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700744 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700745 if (mPendingInits.size() > 0) {
746 // If there are pending init operations, we process those
747 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800748 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700749 try {
750 mAlarmManager.cancel(mRunInitIntent);
751 mRunInitIntent.send();
752 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800753 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700754 // can't really do more than bail here
755 }
756 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800757 // Don't run backups now if we're disabled or not yet
758 // fully set up.
759 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800760 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700761
762 // Acquire the wakelock and pass it to the backup thread. it will
763 // be released once backup concludes.
764 mWakelock.acquire();
765
766 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
767 mBackupHandler.sendMessage(msg);
768 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800769 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700770 }
771 }
772 }
773 }
774 }
775 }
776
777 private class RunInitializeReceiver extends BroadcastReceiver {
778 public void onReceive(Context context, Intent intent) {
779 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
780 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800781 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700782
783 // Acquire the wakelock and pass it to the init thread. it will
784 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700785 mWakelock.acquire();
786
Christopher Tate4cc86e12009-09-21 19:36:51 -0700787 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700788 mBackupHandler.sendMessage(msg);
789 }
790 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700791 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700792 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700793
Christopher Tate73e02522009-07-15 14:18:26 -0700794 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800795 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700796
Christopher Tate84725812010-02-04 15:52:40 -0800797 // Remember our ancestral dataset
798 mTokenFile = new File(mBaseStateDir, "ancestral");
799 try {
800 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800801 int version = tf.readInt();
802 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
803 mAncestralToken = tf.readLong();
804 mCurrentToken = tf.readLong();
805
806 int numPackages = tf.readInt();
807 if (numPackages >= 0) {
808 mAncestralPackages = new HashSet<String>();
809 for (int i = 0; i < numPackages; i++) {
810 String pkgName = tf.readUTF();
811 mAncestralPackages.add(pkgName);
812 }
813 }
814 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800815 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800816 } catch (FileNotFoundException fnf) {
817 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800818 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800819 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800820 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800821 }
822
Christopher Tatee97e8072009-07-15 16:45:50 -0700823 // Keep a log of what apps we've ever backed up. Because we might have
824 // rebooted in the middle of an operation that was removing something from
825 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700826 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700827 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700828
Christopher Tatee97e8072009-07-15 16:45:50 -0700829 // If we were in the middle of removing something from the ever-backed-up
830 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700831 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700832 if (tempProcessedFile.exists()) {
833 tempProcessedFile.delete();
834 }
835
Dan Egnor852f8e42009-09-30 11:20:45 -0700836 // If there are previous contents, parse them out then start a new
837 // file to continue the recordkeeping.
838 if (mEverStored.exists()) {
839 RandomAccessFile temp = null;
840 RandomAccessFile in = null;
841
842 try {
843 temp = new RandomAccessFile(tempProcessedFile, "rws");
844 in = new RandomAccessFile(mEverStored, "r");
845
846 while (true) {
847 PackageInfo info;
848 String pkg = in.readUTF();
849 try {
850 info = mPackageManager.getPackageInfo(pkg, 0);
851 mEverStoredApps.add(pkg);
852 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800853 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700854 } catch (NameNotFoundException e) {
855 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800856 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700857 }
858 }
859 } catch (EOFException e) {
860 // Once we've rewritten the backup history log, atomically replace the
861 // old one with the new one then reopen the file for continuing use.
862 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800863 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700864 }
865 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800866 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700867 } finally {
868 try { if (temp != null) temp.close(); } catch (IOException e) {}
869 try { if (in != null) in.close(); } catch (IOException e) {}
870 }
871 }
872
Christopher Tate73e02522009-07-15 14:18:26 -0700873 // Register for broadcasts about package install, etc., so we can
874 // update the provider list.
875 IntentFilter filter = new IntentFilter();
876 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
877 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
878 filter.addDataScheme("package");
879 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800880 // Register for events related to sdcard installation.
881 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800882 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
883 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800884 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700885 }
886
Christopher Tatecde87f42009-06-12 12:55:53 -0700887 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700888 for (File f : mJournalDir.listFiles()) {
889 if (mJournal == null || f.compareTo(mJournal) != 0) {
890 // This isn't the current journal, so it must be a leftover. Read
891 // out the package names mentioned there and schedule them for
892 // backup.
893 RandomAccessFile in = null;
894 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400895 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700896 in = new RandomAccessFile(f, "r");
897 while (true) {
898 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400899 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700900 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700901 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700902 } catch (EOFException e) {
903 // no more data; we're done
904 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800905 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700906 } finally {
907 // close/delete the file
908 try { if (in != null) in.close(); } catch (IOException e) {}
909 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700910 }
911 }
912 }
913 }
914
Christopher Tate2efd2db2011-07-19 16:32:49 -0700915 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
916 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
917 }
918
919 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
920 try {
921 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
922 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
923 return keyFactory.generateSecret(ks);
924 } catch (InvalidKeySpecException e) {
925 Slog.e(TAG, "Invalid key spec for PBKDF2!");
926 } catch (NoSuchAlgorithmException e) {
927 Slog.e(TAG, "PBKDF2 unavailable!");
928 }
929 return null;
930 }
931
932 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
933 SecretKey key = buildPasswordKey(pw, salt, rounds);
934 if (key != null) {
935 return byteArrayToHex(key.getEncoded());
936 }
937 return null;
938 }
939
940 private String byteArrayToHex(byte[] data) {
941 StringBuilder buf = new StringBuilder(data.length * 2);
942 for (int i = 0; i < data.length; i++) {
943 buf.append(Byte.toHexString(data[i], true));
944 }
945 return buf.toString();
946 }
947
948 private byte[] hexToByteArray(String digits) {
949 final int bytes = digits.length() / 2;
950 if (2*bytes != digits.length()) {
951 throw new IllegalArgumentException("Hex string must have an even number of digits");
952 }
953
954 byte[] result = new byte[bytes];
955 for (int i = 0; i < digits.length(); i += 2) {
956 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
957 }
958 return result;
959 }
960
961 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
962 char[] mkAsChar = new char[pwBytes.length];
963 for (int i = 0; i < pwBytes.length; i++) {
964 mkAsChar[i] = (char) pwBytes[i];
965 }
966
967 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
968 return checksum.getEncoded();
969 }
970
971 // Used for generating random salts or passwords
972 private byte[] randomBytes(int bits) {
973 byte[] array = new byte[bits / 8];
974 mRng.nextBytes(array);
975 return array;
976 }
977
978 // Backup password management
979 boolean passwordMatchesSaved(String candidatePw, int rounds) {
980 if (mPasswordHash == null) {
981 // no current password case -- require that 'currentPw' be null or empty
982 if (candidatePw == null || "".equals(candidatePw)) {
983 return true;
984 } // else the non-empty candidate does not match the empty stored pw
985 } else {
986 // hash the stated current pw and compare to the stored one
987 if (candidatePw != null && candidatePw.length() > 0) {
988 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
989 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
990 // candidate hash matches the stored hash -- the password matches
991 return true;
992 }
993 } // else the stored pw is nonempty but the candidate is empty; no match
994 }
995 return false;
996 }
997
998 @Override
999 public boolean setBackupPassword(String currentPw, String newPw) {
1000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1001 "setBackupPassword");
1002
1003 // If the supplied pw doesn't hash to the the saved one, fail
1004 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1005 return false;
1006 }
1007
1008 // Clearing the password is okay
1009 if (newPw == null || newPw.isEmpty()) {
1010 if (mPasswordHashFile.exists()) {
1011 if (!mPasswordHashFile.delete()) {
1012 // Unable to delete the old pw file, so fail
1013 Slog.e(TAG, "Unable to clear backup password");
1014 return false;
1015 }
1016 }
1017 mPasswordHash = null;
1018 mPasswordSalt = null;
1019 return true;
1020 }
1021
1022 try {
1023 // Okay, build the hash of the new backup password
1024 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1025 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1026
1027 OutputStream pwf = null, buffer = null;
1028 DataOutputStream out = null;
1029 try {
1030 pwf = new FileOutputStream(mPasswordHashFile);
1031 buffer = new BufferedOutputStream(pwf);
1032 out = new DataOutputStream(buffer);
1033 // integer length of the salt array, followed by the salt,
1034 // then the hex pw hash string
1035 out.writeInt(salt.length);
1036 out.write(salt);
1037 out.writeUTF(newPwHash);
1038 out.flush();
1039 mPasswordHash = newPwHash;
1040 mPasswordSalt = salt;
1041 return true;
1042 } finally {
1043 if (out != null) out.close();
1044 if (buffer != null) buffer.close();
1045 if (pwf != null) pwf.close();
1046 }
1047 } catch (IOException e) {
1048 Slog.e(TAG, "Unable to set backup password");
1049 }
1050 return false;
1051 }
1052
1053 @Override
1054 public boolean hasBackupPassword() {
1055 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1056 "hasBackupPassword");
1057 return (mPasswordHash != null && mPasswordHash.length() > 0);
1058 }
1059
Christopher Tate4cc86e12009-09-21 19:36:51 -07001060 // Maintain persistent state around whether need to do an initialize operation.
1061 // Must be called with the queue lock held.
1062 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001063 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001064 + " on transport " + transportName);
1065 try {
1066 IBackupTransport transport = getTransport(transportName);
1067 String transportDirName = transport.transportDirName();
1068 File stateDir = new File(mBaseStateDir, transportDirName);
1069 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1070
1071 if (isPending) {
1072 // We need an init before we can proceed with sending backup data.
1073 // Record that with an entry in our set of pending inits, as well as
1074 // journaling it via creation of a sentinel file.
1075 mPendingInits.add(transportName);
1076 try {
1077 (new FileOutputStream(initPendingFile)).close();
1078 } catch (IOException ioe) {
1079 // Something is badly wrong with our permissions; just try to move on
1080 }
1081 } else {
1082 // No more initialization needed; wipe the journal and reset our state.
1083 initPendingFile.delete();
1084 mPendingInits.remove(transportName);
1085 }
1086 } catch (RemoteException e) {
1087 // can't happen; the transport is local
1088 }
1089 }
1090
Christopher Tated55e18a2009-09-21 10:12:59 -07001091 // Reset all of our bookkeeping, in response to having been told that
1092 // the backend data has been wiped [due to idle expiry, for example],
1093 // so we must re-upload all saved settings.
1094 void resetBackupState(File stateFileDir) {
1095 synchronized (mQueueLock) {
1096 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001097 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001098 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001099
Christopher Tate84725812010-02-04 15:52:40 -08001100 mCurrentToken = 0;
1101 writeRestoreTokens();
1102
Christopher Tated55e18a2009-09-21 10:12:59 -07001103 // Remove all the state files
1104 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001105 // ... but don't touch the needs-init sentinel
1106 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1107 sf.delete();
1108 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001109 }
Christopher Tate45597642011-04-04 16:59:21 -07001110 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001111
Christopher Tate45597642011-04-04 16:59:21 -07001112 // Enqueue a new backup of every participant
1113 int N = mBackupParticipants.size();
1114 for (int i=0; i<N; i++) {
1115 int uid = mBackupParticipants.keyAt(i);
1116 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1117 for (ApplicationInfo app: participants) {
1118 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -07001119 }
1120 }
1121 }
1122
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001123 // Add a transport to our set of available backends. If 'transport' is null, this
1124 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001125 private void registerTransport(String name, IBackupTransport transport) {
1126 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001127 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001128 if (transport != null) {
1129 mTransports.put(name, transport);
1130 } else {
1131 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001132 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001133 mCurrentTransport = null;
1134 }
1135 // Nothing further to do in the unregistration case
1136 return;
1137 }
Christopher Tate91717492009-06-26 21:07:13 -07001138 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001139
1140 // If the init sentinel file exists, we need to be sure to perform the init
1141 // as soon as practical. We also create the state directory at registration
1142 // time to ensure it's present from the outset.
1143 try {
1144 String transportName = transport.transportDirName();
1145 File stateDir = new File(mBaseStateDir, transportName);
1146 stateDir.mkdirs();
1147
1148 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1149 if (initSentinel.exists()) {
1150 synchronized (mQueueLock) {
1151 mPendingInits.add(transportName);
1152
1153 // TODO: pick a better starting time than now + 1 minute
1154 long delay = 1000 * 60; // one minute, in milliseconds
1155 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1156 System.currentTimeMillis() + delay, mRunInitIntent);
1157 }
1158 }
1159 } catch (RemoteException e) {
1160 // can't happen, the transport is local
1161 }
Christopher Tate91717492009-06-26 21:07:13 -07001162 }
1163
Christopher Tate3799bc22009-05-06 16:13:56 -07001164 // ----- Track installation/removal of packages -----
1165 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1166 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001167 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001168
Christopher Tate3799bc22009-05-06 16:13:56 -07001169 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001170 boolean replacing = false;
1171 boolean added = false;
1172 Bundle extras = intent.getExtras();
1173 String pkgList[] = null;
1174 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
1175 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1176 Uri uri = intent.getData();
1177 if (uri == null) {
1178 return;
1179 }
1180 String pkgName = uri.getSchemeSpecificPart();
1181 if (pkgName != null) {
1182 pkgList = new String[] { pkgName };
1183 }
1184 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1185 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001186 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001187 added = true;
1188 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001189 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001190 added = false;
1191 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1192 }
1193 if (pkgList == null || pkgList.length == 0) {
1194 return;
1195 }
1196 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001197 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001198 for (String pkgName : pkgList) {
1199 if (replacing) {
1200 // The package was just upgraded
1201 updatePackageParticipantsLocked(pkgName);
1202 } else {
1203 // The package was just added
1204 addPackageParticipantsLocked(pkgName);
1205 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001206 }
1207 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001208 } else {
1209 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001210 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1211 } else {
1212 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001213 for (String pkgName : pkgList) {
1214 removePackageParticipantsLocked(pkgName);
1215 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001216 }
1217 }
1218 }
1219 }
1220 };
1221
Dan Egnor87a02bc2009-06-17 02:30:10 -07001222 // ----- Track connection to GoogleBackupTransport service -----
1223 ServiceConnection mGoogleConnection = new ServiceConnection() {
1224 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001225 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001226 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001227 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001228 }
1229
1230 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001231 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001232 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001233 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001234 }
1235 };
1236
Christopher Tate181fafa2009-05-14 11:12:14 -07001237 // Add the backup agents in the given package to our set of known backup participants.
1238 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001239 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001240 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001241 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001242 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001243 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001244 }
1245
Christopher Tate181fafa2009-05-14 11:12:14 -07001246 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001247 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001248 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001249 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001250 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001251 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001252 + " uid=" + p.applicationInfo.uid
1253 + " killAfterRestore="
1254 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001255 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001256 }
1257 }
1258
Dan Egnorefe52642009-06-24 00:16:33 -07001259 for (PackageInfo pkg : targetPkgs) {
1260 if (packageName == null || pkg.packageName.equals(packageName)) {
1261 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001262 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001263 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001264 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001265 mBackupParticipants.put(uid, set);
1266 }
Dan Egnorefe52642009-06-24 00:16:33 -07001267 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001268
1269 // If we've never seen this app before, schedule a backup for it
1270 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001271 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001272 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001273 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001274 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001275 }
Christopher Tate487529a2009-04-29 14:03:25 -07001276 }
1277 }
1278
Christopher Tate6785dd82009-06-18 15:58:25 -07001279 // Remove the given package's entry from our known active set. If
1280 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001281 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001282 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001283 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001284 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001285 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001286 } else {
1287 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001288 List<PackageInfo> knownPackages = allAgentPackages();
1289 for (PackageInfo pkg : knownPackages) {
1290 allApps.add(pkg.packageName);
1291 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001292 }
1293 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001294 }
1295
Joe Onorato8ad02812009-05-13 01:41:44 -04001296 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001297 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001298 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001299 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001300 + ") removing " + allPackageNames.size() + " entries");
1301 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001302 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001303 }
1304 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001305 for (String pkg : allPackageNames) {
1306 if (packageName == null || pkg.equals(packageName)) {
1307 int uid = -1;
1308 try {
1309 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1310 uid = info.applicationInfo.uid;
1311 } catch (NameNotFoundException e) {
1312 // we don't know this package name, so just skip it for now
1313 continue;
1314 }
1315
Christopher Tate181fafa2009-05-14 11:12:14 -07001316 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001317 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001318 // Find the existing entry with the same package name, and remove it.
1319 // We can't just remove(app) because the instances are different.
1320 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001321 if (entry.packageName.equals(pkg)) {
1322 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001323 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001324 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001325 break;
1326 }
1327 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001328 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001329 mBackupParticipants.delete(uid);
1330 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001331 }
1332 }
1333 }
1334 }
1335
Christopher Tate181fafa2009-05-14 11:12:14 -07001336 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001337 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001338 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001339 int flags = PackageManager.GET_SIGNATURES;
1340 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1341 int N = packages.size();
1342 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001343 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001344 try {
1345 ApplicationInfo app = pkg.applicationInfo;
1346 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001347 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001348 packages.remove(a);
1349 }
1350 else {
1351 // we will need the shared library path, so look that up and store it here
1352 app = mPackageManager.getApplicationInfo(pkg.packageName,
1353 PackageManager.GET_SHARED_LIBRARY_FILES);
1354 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1355 }
1356 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001357 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001358 }
1359 }
Dan Egnorefe52642009-06-24 00:16:33 -07001360 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001361 }
Christopher Tateaa088442009-06-16 18:25:46 -07001362
Christopher Tate3799bc22009-05-06 16:13:56 -07001363 // Reset the given package's known backup participants. Unlike add/remove, the update
1364 // action cannot be passed a null package name.
1365 void updatePackageParticipantsLocked(String packageName) {
1366 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001367 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001368 return;
1369 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001370 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001371
1372 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001373 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001374 List<String> allAppNames = new ArrayList<String>();
1375 for (PackageInfo pkg : allApps) {
1376 allAppNames.add(pkg.packageName);
1377 }
1378 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001379 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001380 }
1381
Christopher Tate84725812010-02-04 15:52:40 -08001382 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001383 // backed up at least once
1384 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001385 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1386
1387 synchronized (mEverStoredApps) {
1388 if (!mEverStoredApps.add(packageName)) return;
1389
1390 RandomAccessFile out = null;
1391 try {
1392 out = new RandomAccessFile(mEverStored, "rws");
1393 out.seek(out.length());
1394 out.writeUTF(packageName);
1395 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001396 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001397 } finally {
1398 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001399 }
1400 }
1401 }
1402
Christopher Tatee97e8072009-07-15 16:45:50 -07001403 // Remove our awareness of having ever backed up the given package
1404 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001405 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001406
Dan Egnor852f8e42009-09-30 11:20:45 -07001407 synchronized (mEverStoredApps) {
1408 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1409 // we'll recognize on initialization time that the package no longer
1410 // exists and fix it up then.
1411 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1412 RandomAccessFile known = null;
1413 try {
1414 known = new RandomAccessFile(tempKnownFile, "rws");
1415 mEverStoredApps.remove(packageName);
1416 for (String s : mEverStoredApps) {
1417 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001418 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001419 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001420 known.close();
1421 known = null;
1422 if (!tempKnownFile.renameTo(mEverStored)) {
1423 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1424 }
1425 } catch (IOException e) {
1426 // Bad: we couldn't create the new copy. For safety's sake we
1427 // abandon the whole process and remove all what's-backed-up
1428 // state entirely, meaning we'll force a backup pass for every
1429 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001430 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001431 mEverStoredApps.clear();
1432 tempKnownFile.delete();
1433 mEverStored.delete();
1434 } finally {
1435 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001436 }
1437 }
1438 }
1439
Christopher Tateb49ceb32010-02-08 16:22:24 -08001440 // Persistently record the current and ancestral backup tokens as well
1441 // as the set of packages with data [supposedly] available in the
1442 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001443 void writeRestoreTokens() {
1444 try {
1445 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001446
1447 // First, the version number of this record, for futureproofing
1448 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1449
1450 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001451 af.writeLong(mAncestralToken);
1452 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001453
1454 // Now write the set of ancestral packages
1455 if (mAncestralPackages == null) {
1456 af.writeInt(-1);
1457 } else {
1458 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001459 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001460 for (String pkgName : mAncestralPackages) {
1461 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001462 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001463 }
1464 }
Christopher Tate84725812010-02-04 15:52:40 -08001465 af.close();
1466 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001467 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001468 }
1469 }
1470
Dan Egnor87a02bc2009-06-17 02:30:10 -07001471 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001472 private IBackupTransport getTransport(String transportName) {
1473 synchronized (mTransports) {
1474 IBackupTransport transport = mTransports.get(transportName);
1475 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001476 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001477 }
1478 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001479 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001480 }
1481
Christopher Tatedf01dea2009-06-09 20:45:02 -07001482 // fire off a backup agent, blocking until it attaches or times out
1483 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1484 IBackupAgent agent = null;
1485 synchronized(mAgentConnectLock) {
1486 mConnecting = true;
1487 mConnectedAgent = null;
1488 try {
1489 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001490 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001491
1492 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001493 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001494 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1495 while (mConnecting && mConnectedAgent == null
1496 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001497 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001498 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001499 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001500 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001501 return null;
1502 }
1503 }
1504
1505 // if we timed out with no connect, abort and move on
1506 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001507 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001508 return null;
1509 }
1510 agent = mConnectedAgent;
1511 }
1512 } catch (RemoteException e) {
1513 // can't happen
1514 }
1515 }
1516 return agent;
1517 }
1518
Christopher Tatec7b31e32009-06-10 15:49:30 -07001519 // clear an application's data, blocking until the operation completes or times out
1520 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001521 // Don't wipe packages marked allowClearUserData=false
1522 try {
1523 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1524 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001525 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001526 + packageName);
1527 return;
1528 }
1529 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001530 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001531 return;
1532 }
1533
Christopher Tatec7b31e32009-06-10 15:49:30 -07001534 ClearDataObserver observer = new ClearDataObserver();
1535
1536 synchronized(mClearDataLock) {
1537 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001538 try {
1539 mActivityManager.clearApplicationUserData(packageName, observer);
1540 } catch (RemoteException e) {
1541 // can't happen because the activity manager is in this process
1542 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001543
1544 // only wait 10 seconds for the clear data to happen
1545 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1546 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1547 try {
1548 mClearDataLock.wait(5000);
1549 } catch (InterruptedException e) {
1550 // won't happen, but still.
1551 mClearingData = false;
1552 }
1553 }
1554 }
1555 }
1556
1557 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001558 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001559 synchronized(mClearDataLock) {
1560 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001561 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001562 }
1563 }
1564 }
1565
Christopher Tate1bb69062010-02-19 17:02:12 -08001566 // Get the restore-set token for the best-available restore set for this package:
1567 // the active set if possible, else the ancestral one. Returns zero if none available.
1568 long getAvailableRestoreToken(String packageName) {
1569 long token = mAncestralToken;
1570 synchronized (mQueueLock) {
1571 if (mEverStoredApps.contains(packageName)) {
1572 token = mCurrentToken;
1573 }
1574 }
1575 return token;
1576 }
1577
Christopher Tate44a27902010-01-27 17:15:49 -08001578 // -----
1579 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1580 boolean waitUntilOperationComplete(int token) {
1581 int finalState = OP_PENDING;
1582 synchronized (mCurrentOpLock) {
1583 try {
1584 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1585 try {
1586 mCurrentOpLock.wait();
1587 } catch (InterruptedException e) {}
1588 }
1589 } catch (IndexOutOfBoundsException e) {
1590 // the operation has been mysteriously cleared from our
1591 // bookkeeping -- consider this a success and ignore it.
1592 }
1593 }
1594 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001595 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001596 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001597 return finalState == OP_ACKNOWLEDGED;
1598 }
1599
1600 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001602 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001603 synchronized (mCurrentOpLock) {
1604 mCurrentOperations.put(token, OP_PENDING);
1605 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1606 mBackupHandler.sendMessageDelayed(msg, interval);
1607 }
Christopher Tate44a27902010-01-27 17:15:49 -08001608 }
1609
Christopher Tate043dadc2009-06-02 16:11:00 -07001610 // ----- Back up a set of applications via a worker thread -----
1611
Christopher Tate44a27902010-01-27 17:15:49 -08001612 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001613 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001614 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001615 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001616 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001617 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001618
Christopher Tate44a27902010-01-27 17:15:49 -08001619 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001620 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001621 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001622 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001623 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001624
1625 try {
1626 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1627 } catch (RemoteException e) {
1628 // can't happen; the transport is local
1629 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001630 }
1631
Christopher Tate043dadc2009-06-02 16:11:00 -07001632 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001633 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001634 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001635 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001636
Christopher Tate79588342009-06-30 16:11:49 -07001637 // Backups run at background priority
1638 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1639
Christopher Tate043dadc2009-06-02 16:11:00 -07001640 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001641 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001642
Dan Egnor852f8e42009-09-30 11:20:45 -07001643 // If we haven't stored package manager metadata yet, we must init the transport.
1644 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1645 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001646 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001647 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001648 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001649 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001650 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001651 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001652 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001653 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001654 }
Dan Egnor01445162009-09-21 17:04:05 -07001655 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001656
1657 // The package manager doesn't have a proper <application> etc, but since
1658 // it's running here in the system process we can just set up its agent
1659 // directly and use a synthetic BackupRequest. We always run this pass
1660 // because it's cheap and this way we guarantee that we don't get out of
1661 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001662 if (status == BackupConstants.TRANSPORT_OK) {
1663 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1664 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001665 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001666 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1667 status = processOneBackup(pmRequest,
1668 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1669 }
Christopher Tate90967f42009-09-20 15:28:33 -07001670
Dan Egnor01445162009-09-21 17:04:05 -07001671 if (status == BackupConstants.TRANSPORT_OK) {
1672 // Now run all the backups in our queue
1673 status = doQueuedBackups(mTransport);
1674 }
1675
1676 if (status == BackupConstants.TRANSPORT_OK) {
1677 // Tell the transport to finish everything it has buffered
1678 status = mTransport.finishBackup();
1679 if (status == BackupConstants.TRANSPORT_OK) {
1680 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001681 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001682 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001683 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001684 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001685 }
1686 }
1687
Dan Egnor01445162009-09-21 17:04:05 -07001688 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001689 // The backend reports that our dataset has been wiped. We need to
1690 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001691 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001692 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001693 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001694 }
1695 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001696 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001697 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001698 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001699 // If everything actually went through and this is the first time we've
1700 // done a backup, we can now record what the current backup dataset token
1701 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001702 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001703 try {
1704 mCurrentToken = mTransport.getCurrentRestoreSet();
1705 } catch (RemoteException e) { /* cannot happen */ }
1706 writeRestoreTokens();
1707 }
1708
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001709 // If things went wrong, we need to re-stage the apps we had expected
1710 // to be backing up in this pass. This journals the package names in
1711 // the current active pending-backup file, not in the we are holding
1712 // here in mJournal.
1713 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001714 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001715 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001716 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001717 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001718
1719 // We also want to reset the backup schedule based on whatever
1720 // the transport suggests by way of retry/backoff time.
1721 try {
1722 startBackupAlarmsLocked(mTransport.requestBackupTime());
1723 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001724 }
1725
1726 // Either backup was successful, in which case we of course do not need
1727 // this pass's journal any more; or it failed, in which case we just
1728 // re-enqueued all of these packages in the current active journal.
1729 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001730 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001731 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001732 }
1733
Christopher Tatec2af5d32010-02-02 15:18:58 -08001734 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001735 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001736 backupNow();
1737 }
1738
Dan Egnorbb9001c2009-07-27 12:20:13 -07001739 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001740 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001741 }
1742
Dan Egnor01445162009-09-21 17:04:05 -07001743 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001744 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001745 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001746
Christopher Tatec28083a2010-12-14 16:16:44 -08001747 // Verify that the requested app exists; it might be something that
1748 // requested a backup but was then uninstalled. The request was
1749 // journalled and rather than tamper with the journal it's safer
1750 // to sanity-check here.
1751 try {
1752 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1753 } catch (NameNotFoundException e) {
1754 Slog.d(TAG, "Package does not exist; skipping");
1755 continue;
1756 }
1757
Christopher Tate043dadc2009-06-02 16:11:00 -07001758 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001759 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001760 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001761 agent = bindToAgentSynchronous(request.appInfo,
1762 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001763 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001764 int result = processOneBackup(request, agent, transport);
1765 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001766 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001767 } catch (SecurityException ex) {
1768 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001769 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001770 } finally {
1771 try { // unbind even on timeout, just in case
1772 mActivityManager.unbindBackupAgent(request.appInfo);
1773 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001774 }
1775 }
Dan Egnor01445162009-09-21 17:04:05 -07001776
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001777 mWakelock.setWorkSource(null);
1778
Dan Egnor01445162009-09-21 17:04:05 -07001779 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001780 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001781
Dan Egnor01445162009-09-21 17:04:05 -07001782 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1783 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001784 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001785 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001786
Dan Egnorbb9001c2009-07-27 12:20:13 -07001787 File savedStateName = new File(mStateDir, packageName);
1788 File backupDataName = new File(mDataDir, packageName + ".data");
1789 File newStateName = new File(mStateDir, packageName + ".new");
1790
1791 ParcelFileDescriptor savedState = null;
1792 ParcelFileDescriptor backupData = null;
1793 ParcelFileDescriptor newState = null;
1794
1795 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001796 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001797 try {
1798 // Look up the package info & signatures. This is first so that if it
1799 // throws an exception, there's no file setup yet that would need to
1800 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001801 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1802 // The metadata 'package' is synthetic
1803 packInfo = new PackageInfo();
1804 packInfo.packageName = packageName;
1805 } else {
1806 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001807 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001808 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001809
Christopher Tatec7b31e32009-06-10 15:49:30 -07001810 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001811 // the saved-state "file". This is by definition an incremental,
1812 // so we build a saved state file to pass.
1813 savedState = ParcelFileDescriptor.open(savedStateName,
1814 ParcelFileDescriptor.MODE_READ_ONLY |
1815 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001816
Dan Egnorbb9001c2009-07-27 12:20:13 -07001817 backupData = ParcelFileDescriptor.open(backupDataName,
1818 ParcelFileDescriptor.MODE_READ_WRITE |
1819 ParcelFileDescriptor.MODE_CREATE |
1820 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001821
Dan Egnorbb9001c2009-07-27 12:20:13 -07001822 newState = ParcelFileDescriptor.open(newStateName,
1823 ParcelFileDescriptor.MODE_READ_WRITE |
1824 ParcelFileDescriptor.MODE_CREATE |
1825 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001826
Christopher Tate44a27902010-01-27 17:15:49 -08001827 // Initiate the target's backup pass
1828 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001829 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001830 boolean success = waitUntilOperationComplete(token);
1831
1832 if (!success) {
1833 // timeout -- bail out into the failed-transaction logic
1834 throw new RuntimeException("Backup timeout");
1835 }
1836
Dan Egnorbb9001c2009-07-27 12:20:13 -07001837 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001838 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001839 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001840 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001841 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001842 backupDataName.delete();
1843 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001844 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001845 } finally {
1846 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1847 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1848 try { if (newState != null) newState.close(); } catch (IOException e) {}
1849 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001850 synchronized (mCurrentOpLock) {
1851 mCurrentOperations.clear();
1852 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001853 }
1854
1855 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001856 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001857 try {
1858 int size = (int) backupDataName.length();
1859 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001860 if (result == BackupConstants.TRANSPORT_OK) {
1861 backupData = ParcelFileDescriptor.open(backupDataName,
1862 ParcelFileDescriptor.MODE_READ_ONLY);
1863 result = transport.performBackup(packInfo, backupData);
1864 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001865
Dan Egnor83861e72009-09-17 16:17:55 -07001866 // TODO - We call finishBackup() for each application backed up, because
1867 // we need to know now whether it succeeded or failed. Instead, we should
1868 // hold off on finishBackup() until the end, which implies holding off on
1869 // renaming *all* the output state files (see below) until that happens.
1870
Dan Egnor01445162009-09-21 17:04:05 -07001871 if (result == BackupConstants.TRANSPORT_OK) {
1872 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001873 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001874 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001875 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001876 }
1877
1878 // After successful transport, delete the now-stale data
1879 // and juggle the files so that next time we supply the agent
1880 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001881 if (result == BackupConstants.TRANSPORT_OK) {
1882 backupDataName.delete();
1883 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001884 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001885 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001886 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001887 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001888 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001889 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001890 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001891 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001892 } finally {
1893 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001894 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001895
Dan Egnor01445162009-09-21 17:04:05 -07001896 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001897 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001898 }
1899
Christopher Tatedf01dea2009-06-09 20:45:02 -07001900
Christopher Tate4a627c72011-04-01 14:43:32 -07001901 // ----- Full backup to a file/socket -----
1902
1903 class PerformFullBackupTask implements Runnable {
1904 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07001905 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07001906 IFullBackupRestoreObserver mObserver;
1907 boolean mIncludeApks;
1908 boolean mIncludeShared;
1909 boolean mAllApps;
1910 String[] mPackages;
Christopher Tate2efd2db2011-07-19 16:32:49 -07001911 String mUserPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07001912 AtomicBoolean mLatchObject;
1913 File mFilesDir;
1914 File mManifestFile;
1915
Christopher Tate7926a692011-07-11 11:31:57 -07001916 class FullBackupRunner implements Runnable {
1917 PackageInfo mPackage;
1918 IBackupAgent mAgent;
1919 ParcelFileDescriptor mPipe;
1920 int mToken;
1921 boolean mSendApk;
1922
1923 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
1924 int token, boolean sendApk) throws IOException {
1925 mPackage = pack;
1926 mAgent = agent;
1927 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
1928 mToken = token;
1929 mSendApk = sendApk;
1930 }
1931
1932 @Override
1933 public void run() {
1934 try {
1935 BackupDataOutput output = new BackupDataOutput(
1936 mPipe.getFileDescriptor());
1937
1938 if (DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
1939 writeAppManifest(mPackage, mManifestFile, mSendApk);
1940 FullBackup.backupToTar(mPackage.packageName, null, null,
1941 mFilesDir.getAbsolutePath(),
1942 mManifestFile.getAbsolutePath(),
1943 output);
1944
1945 if (mSendApk) {
1946 writeApkToBackup(mPackage, output);
1947 }
1948
1949 if (DEBUG) Slog.d(TAG, "Calling doFullBackup()");
1950 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL);
1951 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
1952 } catch (IOException e) {
1953 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
1954 } catch (RemoteException e) {
1955 Slog.e(TAG, "Remote agent vanished during full backup of "
1956 + mPackage.packageName);
1957 } finally {
1958 try {
1959 mPipe.close();
1960 } catch (IOException e) {}
1961 }
1962 }
1963 }
1964
Christopher Tate4a627c72011-04-01 14:43:32 -07001965 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate2efd2db2011-07-19 16:32:49 -07001966 boolean includeApks, boolean includeShared, String password,
Christopher Tate4a627c72011-04-01 14:43:32 -07001967 boolean doAllApps, String[] packages, AtomicBoolean latch) {
1968 mOutputFile = fd;
1969 mObserver = observer;
1970 mIncludeApks = includeApks;
1971 mIncludeShared = includeShared;
1972 mAllApps = doAllApps;
1973 mPackages = packages;
Christopher Tate2efd2db2011-07-19 16:32:49 -07001974 mUserPassword = password;
Christopher Tate4a627c72011-04-01 14:43:32 -07001975 mLatchObject = latch;
1976
1977 mFilesDir = new File("/data/system");
1978 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1979 }
1980
1981 @Override
1982 public void run() {
1983 final List<PackageInfo> packagesToBackup;
1984
Christopher Tateb0628bf2011-06-02 15:08:13 -07001985 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07001986 sendStartBackup();
1987
1988 // doAllApps supersedes the package set if any
1989 if (mAllApps) {
1990 packagesToBackup = mPackageManager.getInstalledPackages(
1991 PackageManager.GET_SIGNATURES);
1992 } else {
1993 packagesToBackup = new ArrayList<PackageInfo>();
1994 for (String pkgName : mPackages) {
1995 try {
1996 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
1997 PackageManager.GET_SIGNATURES));
1998 } catch (NameNotFoundException e) {
1999 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2000 }
2001 }
2002 }
2003
Christopher Tatea858cb02011-06-03 12:27:51 -07002004 // Cull any packages that have indicated that backups are not permitted.
2005 for (int i = 0; i < packagesToBackup.size(); ) {
2006 PackageInfo info = packagesToBackup.get(i);
2007 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2008 packagesToBackup.remove(i);
2009 } else {
2010 i++;
2011 }
2012 }
2013
Christopher Tate7926a692011-07-11 11:31:57 -07002014 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002015 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002016
Christopher Tate4a627c72011-04-01 14:43:32 -07002017 PackageInfo pkg = null;
2018 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002019 boolean encrypting = (mUserPassword != null && mUserPassword.length() > 0);
2020 boolean compressing = COMPRESS_FULL_BACKUPS;
2021 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002022
2023 // Write the global file header. All strings are UTF-8 encoded; lines end
2024 // with a '\n' byte. Actual backup data begins immediately following the
2025 // final '\n'.
2026 //
2027 // line 1: "ANDROID BACKUP"
2028 // line 2: backup file format version, currently "1"
2029 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002030 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2031 //
2032 // When line 4 is not "none", then additional header data follows:
2033 //
2034 // line 5: user password salt [hex]
2035 // line 6: master key checksum salt [hex]
2036 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2037 // line 8: IV of the user key [hex]
2038 // line 9: master key blob [hex]
2039 // IV of the master key, master key itself, master key checksum hash
2040 //
2041 // The master key checksum is the master key plus its checksum salt, run through
2042 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2043 // correct password for decrypting the archive: the master key decrypted from
2044 // the archive using the user-supplied password is also run through PBKDF2 in
2045 // this way, and if the result does not match the checksum as stored in the
2046 // archive, then we know that the user-supplied password does not match the
2047 // archive's.
2048 StringBuilder headerbuf = new StringBuilder(1024);
2049
Christopher Tate7bdb0962011-07-13 19:30:21 -07002050 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002051 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2052 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002053
2054 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002055 // Set up the encryption stage if appropriate, and emit the correct header
2056 if (encrypting) {
2057 // Verify that the given password matches the currently-active
2058 // backup password, if any
2059 if (hasBackupPassword()) {
2060 if (!passwordMatchesSaved(mUserPassword, PBKDF2_HASH_ROUNDS)) {
2061 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2062 return;
2063 }
2064 }
2065
2066 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2067 } else {
2068 headerbuf.append("none\n");
2069 }
2070
Christopher Tate7bdb0962011-07-13 19:30:21 -07002071 byte[] header = headerbuf.toString().getBytes("UTF-8");
2072 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002073
2074 // Set up the compression stage feeding into the encryption stage (if any)
2075 if (compressing) {
2076 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2077 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2078 }
2079
2080 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002081 } catch (Exception e) {
2082 // Should never happen!
2083 Slog.e(TAG, "Unable to emit archive header", e);
2084 return;
2085 }
2086
Christopher Tateb0628bf2011-06-02 15:08:13 -07002087 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002088 int N = packagesToBackup.size();
2089 for (int i = 0; i < N; i++) {
2090 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002091 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002092 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002093
Christopher Tateb0628bf2011-06-02 15:08:13 -07002094 // Finally, shared storage if requested
2095 if (mIncludeShared) {
2096 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002097 }
2098 } catch (RemoteException e) {
2099 Slog.e(TAG, "App died during full backup");
2100 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002101 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002102 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002103 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002104 mOutputFile.close();
2105 } catch (IOException e) {
2106 /* nothing we can do about this */
2107 }
2108 synchronized (mCurrentOpLock) {
2109 mCurrentOperations.clear();
2110 }
2111 synchronized (mLatchObject) {
2112 mLatchObject.set(true);
2113 mLatchObject.notifyAll();
2114 }
2115 sendEndBackup();
2116 mWakelock.release();
2117 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2118 }
2119 }
2120
Christopher Tate2efd2db2011-07-19 16:32:49 -07002121 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2122 OutputStream ofstream) throws Exception {
2123 // User key will be used to encrypt the master key.
2124 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
2125 SecretKey userKey = buildPasswordKey(mUserPassword, newUserSalt,
2126 PBKDF2_HASH_ROUNDS);
2127
2128 // the master key is random for each backup
2129 byte[] masterPw = new byte[256 / 8];
2130 mRng.nextBytes(masterPw);
2131 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2132
2133 // primary encryption of the datastream with the random key
2134 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2135 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2136 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2137 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2138
2139 // line 4: name of encryption algorithm
2140 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2141 headerbuf.append('\n');
2142 // line 5: user password salt [hex]
2143 headerbuf.append(byteArrayToHex(newUserSalt));
2144 headerbuf.append('\n');
2145 // line 6: master key checksum salt [hex]
2146 headerbuf.append(byteArrayToHex(checksumSalt));
2147 headerbuf.append('\n');
2148 // line 7: number of PBKDF2 rounds used [decimal]
2149 headerbuf.append(PBKDF2_HASH_ROUNDS);
2150 headerbuf.append('\n');
2151
2152 // line 8: IV of the user key [hex]
2153 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2154 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2155
2156 byte[] IV = mkC.getIV();
2157 headerbuf.append(byteArrayToHex(IV));
2158 headerbuf.append('\n');
2159
2160 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2161 // [byte] IV length = Niv
2162 // [array of Niv bytes] IV itself
2163 // [byte] master key length = Nmk
2164 // [array of Nmk bytes] master key itself
2165 // [byte] MK checksum hash length = Nck
2166 // [array of Nck bytes] master key checksum hash
2167 //
2168 // The checksum is the (master key + checksum salt), run through the
2169 // stated number of PBKDF2 rounds
2170 IV = c.getIV();
2171 byte[] mk = masterKeySpec.getEncoded();
2172 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2173 checksumSalt, PBKDF2_HASH_ROUNDS);
2174
2175 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2176 + checksum.length + 3);
2177 DataOutputStream mkOut = new DataOutputStream(blob);
2178 mkOut.writeByte(IV.length);
2179 mkOut.write(IV);
2180 mkOut.writeByte(mk.length);
2181 mkOut.write(mk);
2182 mkOut.writeByte(checksum.length);
2183 mkOut.write(checksum);
2184 mkOut.flush();
2185 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2186 headerbuf.append(byteArrayToHex(encryptedMk));
2187 headerbuf.append('\n');
2188
2189 return finalOutput;
2190 }
2191
2192 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002193 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002194 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2195
2196 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2197 IApplicationThread.BACKUP_MODE_FULL);
2198 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002199 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002200 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002201 pipes = ParcelFileDescriptor.createPipe();
2202
Christopher Tateb0628bf2011-06-02 15:08:13 -07002203 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002204 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002205 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2206 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2207 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2208
2209 sendOnBackupPackage(pkg.packageName);
2210
Christopher Tate7926a692011-07-11 11:31:57 -07002211 final int token = generateToken();
2212 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2213 token, sendApk);
2214 pipes[1].close(); // the runner has dup'd it
2215 pipes[1] = null;
2216 Thread t = new Thread(runner);
2217 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002218
Christopher Tate7926a692011-07-11 11:31:57 -07002219 // Now pull data from the app and stuff it into the compressor
2220 try {
2221 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2222 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002223
Christopher Tate7926a692011-07-11 11:31:57 -07002224 byte[] buffer = new byte[16 * 1024];
2225 int chunkTotal;
2226 while ((chunkTotal = in.readInt()) > 0) {
2227 while (chunkTotal > 0) {
2228 int toRead = (chunkTotal > buffer.length)
2229 ? buffer.length : chunkTotal;
2230 int nRead = in.read(buffer, 0, toRead);
2231 out.write(buffer, 0, nRead);
2232 chunkTotal -= nRead;
2233 }
2234 }
2235 } catch (IOException e) {
2236 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002237 }
2238
Christopher Tateb0628bf2011-06-02 15:08:13 -07002239 if (!waitUntilOperationComplete(token)) {
2240 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2241 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002242 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002243 }
Christopher Tate7926a692011-07-11 11:31:57 -07002244
Christopher Tateb0628bf2011-06-02 15:08:13 -07002245 } catch (IOException e) {
2246 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002247 } finally {
2248 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002249 // flush after every package
2250 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002251 if (pipes != null) {
2252 if (pipes[0] != null) pipes[0].close();
2253 if (pipes[1] != null) pipes[1].close();
2254 }
Christopher Tate7926a692011-07-11 11:31:57 -07002255 } catch (IOException e) {
2256 Slog.w(TAG, "Error bringing down backup stack");
2257 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002258 }
2259 } else {
2260 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2261 }
2262 tearDown(pkg);
2263 }
2264
Christopher Tate79ec80d2011-06-24 14:58:49 -07002265 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2266 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2267 final String appSourceDir = pkg.applicationInfo.sourceDir;
2268 final String apkDir = new File(appSourceDir).getParent();
2269 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2270 apkDir, appSourceDir, output);
2271
2272 // Save associated .obb content if it exists and we did save the apk
2273 // check for .obb and save those too
2274 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2275 if (obbDir != null) {
2276 if (DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
2277 File[] obbFiles = obbDir.listFiles();
2278 if (obbFiles != null) {
2279 final String obbDirName = obbDir.getAbsolutePath();
2280 for (File obb : obbFiles) {
2281 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2282 obbDirName, obb.getAbsolutePath(), output);
2283 }
2284 }
2285 }
2286 }
2287
Christopher Tateb0628bf2011-06-02 15:08:13 -07002288 private void backupSharedStorage() throws RemoteException {
2289 PackageInfo pkg = null;
2290 try {
2291 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2292 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2293 IApplicationThread.BACKUP_MODE_FULL);
2294 if (agent != null) {
2295 sendOnBackupPackage("Shared storage");
2296
2297 final int token = generateToken();
2298 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002299 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002300 if (!waitUntilOperationComplete(token)) {
2301 Slog.e(TAG, "Full backup failed on shared storage");
2302 } else {
2303 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2304 }
2305 } else {
2306 Slog.e(TAG, "Could not bind to shared storage backup agent");
2307 }
2308 } catch (NameNotFoundException e) {
2309 Slog.e(TAG, "Shared storage backup package not found");
2310 } finally {
2311 tearDown(pkg);
2312 }
2313 }
2314
Christopher Tate4a627c72011-04-01 14:43:32 -07002315 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2316 throws IOException {
2317 // Manifest format. All data are strings ending in LF:
2318 // BACKUP_MANIFEST_VERSION, currently 1
2319 //
2320 // Version 1:
2321 // package name
2322 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002323 // platform versionCode
2324 // getInstallerPackageName() for this package (maybe empty)
2325 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002326 // number of signatures == N
2327 // N*: signature byte array in ascii format per Signature.toCharsString()
2328 StringBuilder builder = new StringBuilder(4096);
2329 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2330
2331 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2332 printer.println(pkg.packageName);
2333 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002334 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2335
2336 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2337 printer.println((installerName != null) ? installerName : "");
2338
Christopher Tate4a627c72011-04-01 14:43:32 -07002339 printer.println(withApk ? "1" : "0");
2340 if (pkg.signatures == null) {
2341 printer.println("0");
2342 } else {
2343 printer.println(Integer.toString(pkg.signatures.length));
2344 for (Signature sig : pkg.signatures) {
2345 printer.println(sig.toCharsString());
2346 }
2347 }
2348
2349 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002350 outstream.write(builder.toString().getBytes());
2351 outstream.close();
2352 }
2353
2354 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002355 if (pkg != null) {
2356 final ApplicationInfo app = pkg.applicationInfo;
2357 if (app != null) {
2358 try {
2359 // unbind and tidy up even on timeout or failure, just in case
2360 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002361
Christopher Tateb0628bf2011-06-02 15:08:13 -07002362 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002363 if (app.uid != Process.SYSTEM_UID
2364 && app.uid != Process.PHONE_UID) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002365 if (DEBUG) Slog.d(TAG, "Backup complete, killing host process");
2366 mActivityManager.killApplicationProcess(app.processName, app.uid);
2367 } else {
2368 if (DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
2369 }
2370 } catch (RemoteException e) {
2371 Slog.d(TAG, "Lost app trying to shut down");
2372 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002373 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002374 }
2375 }
2376
2377 // wrappers for observer use
2378 void sendStartBackup() {
2379 if (mObserver != null) {
2380 try {
2381 mObserver.onStartBackup();
2382 } catch (RemoteException e) {
2383 Slog.w(TAG, "full backup observer went away: startBackup");
2384 mObserver = null;
2385 }
2386 }
2387 }
2388
2389 void sendOnBackupPackage(String name) {
2390 if (mObserver != null) {
2391 try {
2392 // TODO: use a more user-friendly name string
2393 mObserver.onBackupPackage(name);
2394 } catch (RemoteException e) {
2395 Slog.w(TAG, "full backup observer went away: backupPackage");
2396 mObserver = null;
2397 }
2398 }
2399 }
2400
2401 void sendEndBackup() {
2402 if (mObserver != null) {
2403 try {
2404 mObserver.onEndBackup();
2405 } catch (RemoteException e) {
2406 Slog.w(TAG, "full backup observer went away: endBackup");
2407 mObserver = null;
2408 }
2409 }
2410 }
2411 }
2412
2413
Christopher Tate75a99702011-05-18 16:28:19 -07002414 // ----- Full restore from a file/socket -----
2415
2416 // Description of a file in the restore datastream
2417 static class FileMetadata {
2418 String packageName; // name of the owning app
2419 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002420 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002421 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2422 String path; // subpath within the semantic domain
2423 long mode; // e.g. 0666 (actually int)
2424 long mtime; // last mod time, UTC time_t (actually int)
2425 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002426
2427 @Override
2428 public String toString() {
2429 StringBuilder sb = new StringBuilder(128);
2430 sb.append("FileMetadata{");
2431 sb.append(packageName); sb.append(',');
2432 sb.append(type); sb.append(',');
2433 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2434 sb.append(size);
2435 sb.append('}');
2436 return sb.toString();
2437 }
Christopher Tate75a99702011-05-18 16:28:19 -07002438 }
2439
2440 enum RestorePolicy {
2441 IGNORE,
2442 ACCEPT,
2443 ACCEPT_IF_APK
2444 }
2445
2446 class PerformFullRestoreTask implements Runnable {
2447 ParcelFileDescriptor mInputFile;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002448 String mUserPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002449 IFullBackupRestoreObserver mObserver;
2450 AtomicBoolean mLatchObject;
2451 IBackupAgent mAgent;
2452 String mAgentPackage;
2453 ApplicationInfo mTargetApp;
2454 ParcelFileDescriptor[] mPipes = null;
2455
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002456 long mBytes;
2457
Christopher Tate75a99702011-05-18 16:28:19 -07002458 // possible handling states for a given package in the restore dataset
2459 final HashMap<String, RestorePolicy> mPackagePolicies
2460 = new HashMap<String, RestorePolicy>();
2461
2462 // installer package names for each encountered app, derived from the manifests
2463 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2464
2465 // Signatures for a given package found in its manifest file
2466 final HashMap<String, Signature[]> mManifestSignatures
2467 = new HashMap<String, Signature[]>();
2468
2469 // Packages we've already wiped data on when restoring their first file
2470 final HashSet<String> mClearedPackages = new HashSet<String>();
2471
Christopher Tate2efd2db2011-07-19 16:32:49 -07002472 PerformFullRestoreTask(ParcelFileDescriptor fd, String password,
2473 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002474 mInputFile = fd;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002475 mUserPassword = password;
Christopher Tate75a99702011-05-18 16:28:19 -07002476 mObserver = observer;
2477 mLatchObject = latch;
2478 mAgent = null;
2479 mAgentPackage = null;
2480 mTargetApp = null;
2481
2482 // Which packages we've already wiped data on. We prepopulate this
2483 // with a whitelist of packages known to be unclearable.
2484 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002485 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002486
Christopher Tate75a99702011-05-18 16:28:19 -07002487 }
2488
2489 class RestoreFileRunnable implements Runnable {
2490 IBackupAgent mAgent;
2491 FileMetadata mInfo;
2492 ParcelFileDescriptor mSocket;
2493 int mToken;
2494
2495 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2496 ParcelFileDescriptor socket, int token) throws IOException {
2497 mAgent = agent;
2498 mInfo = info;
2499 mToken = token;
2500
2501 // This class is used strictly for process-local binder invocations. The
2502 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2503 // do not automatically get a 'dup'ed descriptor that we can can continue
2504 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2505 // before proceeding to do the restore.
2506 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2507 }
2508
2509 @Override
2510 public void run() {
2511 try {
2512 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2513 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2514 mToken, mBackupManagerBinder);
2515 } catch (RemoteException e) {
2516 // never happens; this is used strictly for local binder calls
2517 }
2518 }
2519 }
2520
2521 @Override
2522 public void run() {
2523 Slog.i(TAG, "--- Performing full-dataset restore ---");
2524 sendStartRestore();
2525
Christopher Tateb0628bf2011-06-02 15:08:13 -07002526 // Are we able to restore shared-storage data?
2527 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2528 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2529 }
2530
Christopher Tate2efd2db2011-07-19 16:32:49 -07002531 FileInputStream rawInStream = null;
2532 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002533 try {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002534 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002535 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002536 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2537 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002538
2539 // First, parse out the unencrypted/uncompressed header
2540 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002541 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002542 final InputStream in;
2543
2544 boolean okay = false;
2545 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2546 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002547 rawDataIn.readFully(streamHeader);
2548 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2549 if (Arrays.equals(magicBytes, streamHeader)) {
2550 // okay, header looks good. now parse out the rest of the fields.
2551 String s = readHeaderLine(rawInStream);
2552 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2553 // okay, it's a version we recognize
2554 s = readHeaderLine(rawInStream);
2555 compressed = (Integer.parseInt(s) != 0);
2556 s = readHeaderLine(rawInStream);
2557 if (s.equals("none")) {
2558 // no more header to parse; we're good to go
2559 okay = true;
2560 } else if (mUserPassword != null && mUserPassword.length() > 0) {
2561 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2562 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002563 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002564 }
2565 } else Slog.w(TAG, "Archive is encrypted but no password given");
2566 } else Slog.w(TAG, "Wrong header version: " + s);
2567 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002568
2569 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002570 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002571 return;
2572 }
2573
2574 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002575 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002576
2577 boolean didRestore;
2578 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002579 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002580 } while (didRestore);
2581
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002582 if (DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002583 } catch (IOException e) {
2584 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002585 } finally {
2586 tearDownPipes();
2587 tearDownAgent(mTargetApp);
2588
2589 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002590 if (rawDataIn != null) rawDataIn.close();
2591 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002592 mInputFile.close();
2593 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002594 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002595 /* nothing we can do about this */
2596 }
2597 synchronized (mCurrentOpLock) {
2598 mCurrentOperations.clear();
2599 }
2600 synchronized (mLatchObject) {
2601 mLatchObject.set(true);
2602 mLatchObject.notifyAll();
2603 }
2604 sendEndRestore();
2605 mWakelock.release();
2606 if (DEBUG) Slog.d(TAG, "Full restore pass complete.");
2607 }
2608 }
2609
Christopher Tate7bdb0962011-07-13 19:30:21 -07002610 String readHeaderLine(InputStream in) throws IOException {
2611 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002612 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002613 while ((c = in.read()) >= 0) {
2614 if (c == '\n') break; // consume and discard the newlines
2615 buffer.append((char)c);
2616 }
2617 return buffer.toString();
2618 }
2619
Christopher Tate2efd2db2011-07-19 16:32:49 -07002620 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2621 InputStream result = null;
2622 try {
2623 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2624
2625 String userSaltHex = readHeaderLine(rawInStream); // 5
2626 byte[] userSalt = hexToByteArray(userSaltHex);
2627
2628 String ckSaltHex = readHeaderLine(rawInStream); // 6
2629 byte[] ckSalt = hexToByteArray(ckSaltHex);
2630
2631 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2632 String userIvHex = readHeaderLine(rawInStream); // 8
2633
2634 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2635
2636 // decrypt the master key blob
2637 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2638 SecretKey userKey = buildPasswordKey(mUserPassword, userSalt,
2639 rounds);
2640 byte[] IV = hexToByteArray(userIvHex);
2641 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2642 c.init(Cipher.DECRYPT_MODE,
2643 new SecretKeySpec(userKey.getEncoded(), "AES"),
2644 ivSpec);
2645 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2646 byte[] mkBlob = c.doFinal(mkCipher);
2647
2648 // first, the master key IV
2649 int offset = 0;
2650 int len = mkBlob[offset++];
2651 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2652 offset += len;
2653 // then the master key itself
2654 len = mkBlob[offset++];
2655 byte[] mk = Arrays.copyOfRange(mkBlob,
2656 offset, offset + len);
2657 offset += len;
2658 // and finally the master key checksum hash
2659 len = mkBlob[offset++];
2660 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2661 offset, offset + len);
2662
2663 // now validate the decrypted master key against the checksum
2664 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2665 if (Arrays.equals(calculatedCk, mkChecksum)) {
2666 ivSpec = new IvParameterSpec(IV);
2667 c.init(Cipher.DECRYPT_MODE,
2668 new SecretKeySpec(mk, "AES"),
2669 ivSpec);
2670 // Only if all of the above worked properly will 'result' be assigned
2671 result = new CipherInputStream(rawInStream, c);
2672 } else Slog.w(TAG, "Incorrect password");
2673 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2674 } catch (InvalidAlgorithmParameterException e) {
2675 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2676 } catch (BadPaddingException e) {
2677 // This case frequently occurs when the wrong password is used to decrypt
2678 // the master key. Use the identical "incorrect password" log text as is
2679 // used in the checksum failure log in order to avoid providing additional
2680 // information to an attacker.
2681 Slog.w(TAG, "Incorrect password");
2682 } catch (IllegalBlockSizeException e) {
2683 Slog.w(TAG, "Invalid block size in master key");
2684 } catch (NoSuchAlgorithmException e) {
2685 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2686 } catch (NoSuchPaddingException e) {
2687 Slog.e(TAG, "Needed padding mechanism unavailable!");
2688 } catch (InvalidKeyException e) {
2689 Slog.w(TAG, "Illegal password; aborting");
2690 } catch (NumberFormatException e) {
2691 Slog.w(TAG, "Can't parse restore data header");
2692 } catch (IOException e) {
2693 Slog.w(TAG, "Can't read input header");
2694 }
2695
2696 return result;
2697 }
2698
Christopher Tate75a99702011-05-18 16:28:19 -07002699 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2700 FileMetadata info;
2701 try {
2702 info = readTarHeaders(instream);
2703 if (info != null) {
2704 if (DEBUG) {
2705 dumpFileMetadata(info);
2706 }
2707
2708 final String pkg = info.packageName;
2709 if (!pkg.equals(mAgentPackage)) {
2710 // okay, change in package; set up our various
2711 // bookkeeping if we haven't seen it yet
2712 if (!mPackagePolicies.containsKey(pkg)) {
2713 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2714 }
2715
2716 // Clean up the previous agent relationship if necessary,
2717 // and let the observer know we're considering a new app.
2718 if (mAgent != null) {
2719 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2720 tearDownPipes();
2721 tearDownAgent(mTargetApp);
2722 mTargetApp = null;
2723 mAgentPackage = null;
2724 }
2725 }
2726
2727 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2728 mPackagePolicies.put(pkg, readAppManifest(info, instream));
2729 mPackageInstallers.put(pkg, info.installerPackageName);
2730 // We've read only the manifest content itself at this point,
2731 // so consume the footer before looping around to the next
2732 // input file
2733 skipTarPadding(info.size, instream);
2734 sendOnRestorePackage(pkg);
2735 } else {
2736 // Non-manifest, so it's actual file data. Is this a package
2737 // we're ignoring?
2738 boolean okay = true;
2739 RestorePolicy policy = mPackagePolicies.get(pkg);
2740 switch (policy) {
2741 case IGNORE:
2742 okay = false;
2743 break;
2744
2745 case ACCEPT_IF_APK:
2746 // If we're in accept-if-apk state, then the first file we
2747 // see MUST be the apk.
2748 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2749 if (DEBUG) Slog.d(TAG, "APK file; installing");
2750 // Try to install the app.
2751 String installerName = mPackageInstallers.get(pkg);
2752 okay = installApk(info, installerName, instream);
2753 // good to go; promote to ACCEPT
2754 mPackagePolicies.put(pkg, (okay)
2755 ? RestorePolicy.ACCEPT
2756 : RestorePolicy.IGNORE);
2757 // At this point we've consumed this file entry
2758 // ourselves, so just strip the tar footer and
2759 // go on to the next file in the input stream
2760 skipTarPadding(info.size, instream);
2761 return true;
2762 } else {
2763 // File data before (or without) the apk. We can't
2764 // handle it coherently in this case so ignore it.
2765 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2766 okay = false;
2767 }
2768 break;
2769
2770 case ACCEPT:
2771 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2772 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
2773 // we can take the data without the apk, so we
2774 // *want* to do so. skip the apk by declaring this
2775 // one file not-okay without changing the restore
2776 // policy for the package.
2777 okay = false;
2778 }
2779 break;
2780
2781 default:
2782 // Something has gone dreadfully wrong when determining
2783 // the restore policy from the manifest. Ignore the
2784 // rest of this package's data.
2785 Slog.e(TAG, "Invalid policy from manifest");
2786 okay = false;
2787 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2788 break;
2789 }
2790
2791 // If the policy is satisfied, go ahead and set up to pipe the
2792 // data to the agent.
2793 if (DEBUG && okay && mAgent != null) {
2794 Slog.i(TAG, "Reusing existing agent instance");
2795 }
2796 if (okay && mAgent == null) {
2797 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
2798
2799 try {
2800 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
2801
2802 // If we haven't sent any data to this app yet, we probably
2803 // need to clear it first. Check that.
2804 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002805 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07002806 // responsible for coherently managing a full
2807 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07002808 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07002809 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
2810 clearApplicationDataSynchronous(pkg);
2811 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002812 if (DEBUG) Slog.d(TAG, "backup agent ("
2813 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07002814 }
2815 mClearedPackages.add(pkg);
2816 } else {
2817 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
2818 }
2819
2820 // All set; now set up the IPC and launch the agent
2821 setUpPipes();
2822 mAgent = bindToAgentSynchronous(mTargetApp,
2823 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
2824 mAgentPackage = pkg;
2825 } catch (IOException e) {
2826 // fall through to error handling
2827 } catch (NameNotFoundException e) {
2828 // fall through to error handling
2829 }
2830
2831 if (mAgent == null) {
2832 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
2833 okay = false;
2834 tearDownPipes();
2835 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2836 }
2837 }
2838
2839 // Sanity check: make sure we never give data to the wrong app. This
2840 // should never happen but a little paranoia here won't go amiss.
2841 if (okay && !pkg.equals(mAgentPackage)) {
2842 Slog.e(TAG, "Restoring data for " + pkg
2843 + " but agent is for " + mAgentPackage);
2844 okay = false;
2845 }
2846
2847 // At this point we have an agent ready to handle the full
2848 // restore data as well as a pipe for sending data to
2849 // that agent. Tell the agent to start reading from the
2850 // pipe.
2851 if (okay) {
2852 boolean agentSuccess = true;
2853 long toCopy = info.size;
2854 final int token = generateToken();
2855 try {
2856 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
2857 + info.path);
2858 prepareOperationTimeout(token,
2859 TIMEOUT_FULL_BACKUP_INTERVAL);
2860 // fire up the app's agent listening on the socket. If
2861 // the agent is running in the system process we can't
2862 // just invoke it asynchronously, so we provide a thread
2863 // for it here.
2864 if (mTargetApp.processName.equals("system")) {
2865 Slog.d(TAG, "system process agent - spinning a thread");
2866 RestoreFileRunnable runner = new RestoreFileRunnable(
2867 mAgent, info, mPipes[0], token);
2868 new Thread(runner).start();
2869 } else {
2870 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
2871 info.domain, info.path, info.mode, info.mtime,
2872 token, mBackupManagerBinder);
2873 }
2874 } catch (IOException e) {
2875 // couldn't dup the socket for a process-local restore
2876 Slog.d(TAG, "Couldn't establish restore");
2877 agentSuccess = false;
2878 okay = false;
2879 } catch (RemoteException e) {
2880 // whoops, remote agent went away. We'll eat the content
2881 // ourselves, then, and not copy it over.
2882 Slog.e(TAG, "Agent crashed during full restore");
2883 agentSuccess = false;
2884 okay = false;
2885 }
2886
2887 // Copy over the data if the agent is still good
2888 if (okay) {
2889 boolean pipeOkay = true;
2890 FileOutputStream pipe = new FileOutputStream(
2891 mPipes[1].getFileDescriptor());
2892 if (DEBUG) Slog.d(TAG, "Piping data to agent");
2893 while (toCopy > 0) {
2894 int toRead = (toCopy > buffer.length)
2895 ? buffer.length : (int)toCopy;
2896 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002897 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002898 if (nRead <= 0) break;
2899 toCopy -= nRead;
2900
2901 // send it to the output pipe as long as things
2902 // are still good
2903 if (pipeOkay) {
2904 try {
2905 pipe.write(buffer, 0, nRead);
2906 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002907 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002908 pipeOkay = false;
2909 }
2910 }
2911 }
2912
2913 // done sending that file! Now we just need to consume
2914 // the delta from info.size to the end of block.
2915 skipTarPadding(info.size, instream);
2916
2917 // and now that we've sent it all, wait for the remote
2918 // side to acknowledge receipt
2919 agentSuccess = waitUntilOperationComplete(token);
2920 }
2921
2922 // okay, if the remote end failed at any point, deal with
2923 // it by ignoring the rest of the restore on it
2924 if (!agentSuccess) {
2925 mBackupHandler.removeMessages(MSG_TIMEOUT);
2926 tearDownPipes();
2927 tearDownAgent(mTargetApp);
2928 mAgent = null;
2929 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2930 }
2931 }
2932
2933 // Problems setting up the agent communication, or an already-
2934 // ignored package: skip to the next tar stream entry by
2935 // reading and discarding this file.
2936 if (!okay) {
2937 if (DEBUG) Slog.d(TAG, "[discarding file content]");
2938 long bytesToConsume = (info.size + 511) & ~511;
2939 while (bytesToConsume > 0) {
2940 int toRead = (bytesToConsume > buffer.length)
2941 ? buffer.length : (int)bytesToConsume;
2942 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002943 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002944 if (nRead <= 0) break;
2945 bytesToConsume -= nRead;
2946 }
2947 }
2948 }
2949 }
2950 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002951 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002952 // treat as EOF
2953 info = null;
2954 }
2955
2956 return (info != null);
2957 }
2958
2959 void setUpPipes() throws IOException {
2960 mPipes = ParcelFileDescriptor.createPipe();
2961 }
2962
2963 void tearDownPipes() {
2964 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002965 try {
2966 mPipes[0].close();
2967 mPipes[0] = null;
2968 mPipes[1].close();
2969 mPipes[1] = null;
2970 } catch (IOException e) {
2971 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002972 }
2973 mPipes = null;
2974 }
2975 }
2976
2977 void tearDownAgent(ApplicationInfo app) {
2978 if (mAgent != null) {
2979 try {
2980 // unbind and tidy up even on timeout or failure, just in case
2981 mActivityManager.unbindBackupAgent(app);
2982
2983 // The agent was running with a stub Application object, so shut it down.
2984 // !!! We hardcode the confirmation UI's package name here rather than use a
2985 // manifest flag! TODO something less direct.
2986 if (app.uid != Process.SYSTEM_UID
2987 && !app.packageName.equals("com.android.backupconfirm")) {
2988 if (DEBUG) Slog.d(TAG, "Killing host process");
2989 mActivityManager.killApplicationProcess(app.processName, app.uid);
2990 } else {
2991 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
2992 }
2993 } catch (RemoteException e) {
2994 Slog.d(TAG, "Lost app trying to shut down");
2995 }
2996 mAgent = null;
2997 }
2998 }
2999
3000 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3001 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003002 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003003 int mResult;
3004
3005 public void reset() {
3006 synchronized (mDone) {
3007 mDone.set(false);
3008 }
3009 }
3010
3011 public void waitForCompletion() {
3012 synchronized (mDone) {
3013 while (mDone.get() == false) {
3014 try {
3015 mDone.wait();
3016 } catch (InterruptedException e) { }
3017 }
3018 }
3019 }
3020
3021 int getResult() {
3022 return mResult;
3023 }
3024
3025 @Override
3026 public void packageInstalled(String packageName, int returnCode)
3027 throws RemoteException {
3028 synchronized (mDone) {
3029 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003030 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003031 mDone.set(true);
3032 mDone.notifyAll();
3033 }
3034 }
3035 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003036
3037 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3038 final AtomicBoolean mDone = new AtomicBoolean();
3039 int mResult;
3040
3041 public void reset() {
3042 synchronized (mDone) {
3043 mDone.set(false);
3044 }
3045 }
3046
3047 public void waitForCompletion() {
3048 synchronized (mDone) {
3049 while (mDone.get() == false) {
3050 try {
3051 mDone.wait();
3052 } catch (InterruptedException e) { }
3053 }
3054 }
3055 }
3056
3057 @Override
3058 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3059 synchronized (mDone) {
3060 mResult = returnCode;
3061 mDone.set(true);
3062 mDone.notifyAll();
3063 }
3064 }
3065 }
3066
Christopher Tate75a99702011-05-18 16:28:19 -07003067 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003068 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003069
3070 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3071 boolean okay = true;
3072
3073 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3074
3075 // The file content is an .apk file. Copy it out to a staging location and
3076 // attempt to install it.
3077 File apkFile = new File(mDataDir, info.packageName);
3078 try {
3079 FileOutputStream apkStream = new FileOutputStream(apkFile);
3080 byte[] buffer = new byte[32 * 1024];
3081 long size = info.size;
3082 while (size > 0) {
3083 long toRead = (buffer.length < size) ? buffer.length : size;
3084 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003085 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003086 apkStream.write(buffer, 0, didRead);
3087 size -= didRead;
3088 }
3089 apkStream.close();
3090
3091 // make sure the installer can read it
3092 apkFile.setReadable(true, false);
3093
3094 // Now install it
3095 Uri packageUri = Uri.fromFile(apkFile);
3096 mInstallObserver.reset();
3097 mPackageManager.installPackage(packageUri, mInstallObserver,
3098 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
3099 mInstallObserver.waitForCompletion();
3100
3101 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3102 // The only time we continue to accept install of data even if the
3103 // apk install failed is if we had already determined that we could
3104 // accept the data regardless.
3105 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3106 okay = false;
3107 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003108 } else {
3109 // Okay, the install succeeded. Make sure it was the right app.
3110 boolean uninstall = false;
3111 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3112 Slog.w(TAG, "Restore stream claimed to include apk for "
3113 + info.packageName + " but apk was really "
3114 + mInstallObserver.mPackageName);
3115 // delete the package we just put in place; it might be fraudulent
3116 okay = false;
3117 uninstall = true;
3118 } else {
3119 try {
3120 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3121 PackageManager.GET_SIGNATURES);
3122 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3123 Slog.w(TAG, "Restore stream contains apk of package "
3124 + info.packageName + " but it disallows backup/restore");
3125 okay = false;
3126 } else {
3127 // So far so good -- do the signatures match the manifest?
3128 Signature[] sigs = mManifestSignatures.get(info.packageName);
3129 if (!signaturesMatch(sigs, pkg)) {
3130 Slog.w(TAG, "Installed app " + info.packageName
3131 + " signatures do not match restore manifest");
3132 okay = false;
3133 uninstall = true;
3134 }
3135 }
3136 } catch (NameNotFoundException e) {
3137 Slog.w(TAG, "Install of package " + info.packageName
3138 + " succeeded but now not found");
3139 okay = false;
3140 }
3141 }
3142
3143 // If we're not okay at this point, we need to delete the package
3144 // that we just installed.
3145 if (uninstall) {
3146 mDeleteObserver.reset();
3147 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3148 mDeleteObserver, 0);
3149 mDeleteObserver.waitForCompletion();
3150 }
Christopher Tate75a99702011-05-18 16:28:19 -07003151 }
3152 } catch (IOException e) {
3153 Slog.e(TAG, "Unable to transcribe restored apk for install");
3154 okay = false;
3155 } finally {
3156 apkFile.delete();
3157 }
3158
3159 return okay;
3160 }
3161
3162 // Given an actual file content size, consume the post-content padding mandated
3163 // by the tar format.
3164 void skipTarPadding(long size, InputStream instream) throws IOException {
3165 long partial = (size + 512) % 512;
3166 if (partial > 0) {
3167 byte[] buffer = new byte[512];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003168 int nRead = instream.read(buffer, 0, 512 - (int)partial);
3169 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003170 }
3171 }
3172
3173 // Returns a policy constant; takes a buffer arg to reduce memory churn
3174 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3175 throws IOException {
3176 // Fail on suspiciously large manifest files
3177 if (info.size > 64 * 1024) {
3178 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3179 }
3180 byte[] buffer = new byte[(int) info.size];
3181 int nRead = 0;
3182 while (nRead < info.size) {
3183 nRead += instream.read(buffer, nRead, (int)info.size - nRead);
3184 }
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003185 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003186
3187 RestorePolicy policy = RestorePolicy.IGNORE;
3188 String[] str = new String[1];
3189 int offset = 0;
3190
3191 try {
3192 offset = extractLine(buffer, offset, str);
3193 int version = Integer.parseInt(str[0]);
3194 if (version == BACKUP_MANIFEST_VERSION) {
3195 offset = extractLine(buffer, offset, str);
3196 String manifestPackage = str[0];
3197 // TODO: handle <original-package>
3198 if (manifestPackage.equals(info.packageName)) {
3199 offset = extractLine(buffer, offset, str);
3200 version = Integer.parseInt(str[0]); // app version
3201 offset = extractLine(buffer, offset, str);
3202 int platformVersion = Integer.parseInt(str[0]);
3203 offset = extractLine(buffer, offset, str);
3204 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3205 offset = extractLine(buffer, offset, str);
3206 boolean hasApk = str[0].equals("1");
3207 offset = extractLine(buffer, offset, str);
3208 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003209 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003210 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003211 for (int i = 0; i < numSigs; i++) {
3212 offset = extractLine(buffer, offset, str);
3213 sigs[i] = new Signature(str[0]);
3214 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003215 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003216
3217 // Okay, got the manifest info we need...
3218 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003219 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3220 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003221 // Fall through to IGNORE if the app explicitly disallows backup
3222 final int flags = pkgInfo.applicationInfo.flags;
3223 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3224 // Verify signatures against any installed version; if they
3225 // don't match, then we fall though and ignore the data. The
3226 // signatureMatch() method explicitly ignores the signature
3227 // check for packages installed on the system partition, because
3228 // such packages are signed with the platform cert instead of
3229 // the app developer's cert, so they're different on every
3230 // device.
3231 if (signaturesMatch(sigs, pkgInfo)) {
3232 if (pkgInfo.versionCode >= version) {
3233 Slog.i(TAG, "Sig + version match; taking data");
3234 policy = RestorePolicy.ACCEPT;
3235 } else {
3236 // The data is from a newer version of the app than
3237 // is presently installed. That means we can only
3238 // use it if the matching apk is also supplied.
3239 Slog.d(TAG, "Data version " + version
3240 + " is newer than installed version "
3241 + pkgInfo.versionCode + " - requiring apk");
3242 policy = RestorePolicy.ACCEPT_IF_APK;
3243 }
Christopher Tate75a99702011-05-18 16:28:19 -07003244 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003245 Slog.w(TAG, "Restore manifest signatures do not match "
3246 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003247 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003248 } else {
3249 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3250 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003251 }
3252 } catch (NameNotFoundException e) {
3253 // Okay, the target app isn't installed. We can process
3254 // the restore properly only if the dataset provides the
3255 // apk file and we can successfully install it.
3256 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3257 + " not installed; requiring apk in dataset");
3258 policy = RestorePolicy.ACCEPT_IF_APK;
3259 }
3260
3261 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3262 Slog.i(TAG, "Cannot restore package " + info.packageName
3263 + " without the matching .apk");
3264 }
3265 } else {
3266 Slog.i(TAG, "Missing signature on backed-up package "
3267 + info.packageName);
3268 }
3269 } else {
3270 Slog.i(TAG, "Expected package " + info.packageName
3271 + " but restore manifest claims " + manifestPackage);
3272 }
3273 } else {
3274 Slog.i(TAG, "Unknown restore manifest version " + version
3275 + " for package " + info.packageName);
3276 }
3277 } catch (NumberFormatException e) {
3278 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
3279 }
3280
3281 return policy;
3282 }
3283
3284 // Builds a line from a byte buffer starting at 'offset', and returns
3285 // the index of the next unconsumed data in the buffer.
3286 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3287 final int end = buffer.length;
3288 if (offset >= end) throw new IOException("Incomplete data");
3289
3290 int pos;
3291 for (pos = offset; pos < end; pos++) {
3292 byte c = buffer[pos];
3293 // at LF we declare end of line, and return the next char as the
3294 // starting point for the next time through
3295 if (c == '\n') {
3296 break;
3297 }
3298 }
3299 outStr[0] = new String(buffer, offset, pos - offset);
3300 pos++; // may be pointing an extra byte past the end but that's okay
3301 return pos;
3302 }
3303
3304 void dumpFileMetadata(FileMetadata info) {
3305 if (DEBUG) {
3306 StringBuilder b = new StringBuilder(128);
3307
3308 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003309 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003310 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3311 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3312 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3313 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3314 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3315 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3316 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3317 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3318 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3319 b.append(String.format(" %9d ", info.size));
3320
3321 Date stamp = new Date(info.mtime);
3322 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3323
3324 b.append(info.packageName);
3325 b.append(" :: ");
3326 b.append(info.domain);
3327 b.append(" :: ");
3328 b.append(info.path);
3329
3330 Slog.i(TAG, b.toString());
3331 }
3332 }
3333 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3334 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3335 byte[] block = new byte[512];
3336 FileMetadata info = null;
3337
3338 boolean gotHeader = readTarHeader(instream, block);
3339 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003340 try {
3341 // okay, presume we're okay, and extract the various metadata
3342 info = new FileMetadata();
3343 info.size = extractRadix(block, 124, 12, 8);
3344 info.mtime = extractRadix(block, 136, 12, 8);
3345 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003346
Christopher Tate2efd2db2011-07-19 16:32:49 -07003347 info.path = extractString(block, 345, 155); // prefix
3348 String path = extractString(block, 0, 100);
3349 if (path.length() > 0) {
3350 if (info.path.length() > 0) info.path += '/';
3351 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003352 }
Christopher Tate75a99702011-05-18 16:28:19 -07003353
Christopher Tate2efd2db2011-07-19 16:32:49 -07003354 // tar link indicator field: 1 byte at offset 156 in the header.
3355 int typeChar = block[156];
3356 if (typeChar == 'x') {
3357 // pax extended header, so we need to read that
3358 gotHeader = readPaxExtendedHeader(instream, info);
3359 if (gotHeader) {
3360 // and after a pax extended header comes another real header -- read
3361 // that to find the real file type
3362 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003363 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003364 if (!gotHeader) throw new IOException("Bad or missing pax header");
3365
3366 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003367 }
Christopher Tate75a99702011-05-18 16:28:19 -07003368
Christopher Tate2efd2db2011-07-19 16:32:49 -07003369 switch (typeChar) {
3370 case '0': info.type = BackupAgent.TYPE_FILE; break;
3371 case '5': {
3372 info.type = BackupAgent.TYPE_DIRECTORY;
3373 if (info.size != 0) {
3374 Slog.w(TAG, "Directory entry with nonzero size in header");
3375 info.size = 0;
3376 }
3377 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003378 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003379 case 0: {
3380 // presume EOF
3381 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3382 return null;
3383 }
3384 default: {
3385 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3386 throw new IOException("Unknown entity type " + typeChar);
3387 }
Christopher Tate75a99702011-05-18 16:28:19 -07003388 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003389
3390 // Parse out the path
3391 //
3392 // first: apps/shared/unrecognized
3393 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3394 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3395 // File in shared storage. !!! TODO: implement this.
3396 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3397 info.packageName = "com.android.sharedstoragebackup";
3398 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3399 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3400 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3401 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3402 // App content! Parse out the package name and domain
3403
3404 // strip the apps/ prefix
3405 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3406
3407 // extract the package name
3408 int slash = info.path.indexOf('/');
3409 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3410 info.packageName = info.path.substring(0, slash);
3411 info.path = info.path.substring(slash+1);
3412
3413 // if it's a manifest we're done, otherwise parse out the domains
3414 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3415 slash = info.path.indexOf('/');
3416 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3417 info.domain = info.path.substring(0, slash);
3418 // validate that it's one of the domains we understand
3419 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3420 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3421 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3422 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3423 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3424 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3425 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3426 throw new IOException("Unrecognized domain " + info.domain);
3427 }
3428
3429 info.path = info.path.substring(slash + 1);
3430 }
3431 }
3432 } catch (IOException e) {
3433 if (DEBUG) {
3434 Slog.e(TAG, "Parse error in header. Hexdump:");
3435 HEXLOG(block);
3436 }
3437 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003438 }
3439 }
3440 return info;
3441 }
3442
Christopher Tate2efd2db2011-07-19 16:32:49 -07003443 private void HEXLOG(byte[] block) {
3444 int offset = 0;
3445 int todo = block.length;
3446 StringBuilder buf = new StringBuilder(64);
3447 while (todo > 0) {
3448 buf.append(String.format("%04x ", offset));
3449 int numThisLine = (todo > 16) ? 16 : todo;
3450 for (int i = 0; i < numThisLine; i++) {
3451 buf.append(String.format("%02x ", block[offset+i]));
3452 }
3453 Slog.i("hexdump", buf.toString());
3454 buf.setLength(0);
3455 todo -= numThisLine;
3456 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003457 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003458 }
3459
3460 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3461 int totalRead = 0;
3462 while (totalRead < 512) {
3463 int nRead = instream.read(block, totalRead, 512 - totalRead);
3464 if (nRead >= 0) {
3465 mBytes += nRead;
3466 totalRead += nRead;
3467 } else {
3468 if (totalRead == 0) {
3469 // EOF instead of a new header; we're done
3470 break;
3471 }
3472 throw new IOException("Unable to read full block header, t=" + totalRead);
3473 }
3474 }
3475 return (totalRead == 512);
Christopher Tate75a99702011-05-18 16:28:19 -07003476 }
3477
3478 // overwrites 'info' fields based on the pax extended header
3479 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3480 throws IOException {
3481 // We should never see a pax extended header larger than this
3482 if (info.size > 32*1024) {
3483 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3484 + " - aborting");
3485 throw new IOException("Sanity failure: pax header size " + info.size);
3486 }
3487
3488 // read whole blocks, not just the content size
3489 int numBlocks = (int)((info.size + 511) >> 9);
3490 byte[] data = new byte[numBlocks * 512];
3491 int nRead = instream.read(data);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003492 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003493 if (nRead != data.length) {
3494 return false;
3495 }
3496
3497 final int contentSize = (int) info.size;
3498 int offset = 0;
3499 do {
3500 // extract the line at 'offset'
3501 int eol = offset+1;
3502 while (eol < contentSize && data[eol] != ' ') eol++;
3503 if (eol >= contentSize) {
3504 // error: we just hit EOD looking for the end of the size field
3505 throw new IOException("Invalid pax data");
3506 }
3507 // eol points to the space between the count and the key
3508 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3509 int key = eol + 1; // start of key=value
3510 eol = offset + linelen - 1; // trailing LF
3511 int value;
3512 for (value = key+1; data[value] != '=' && value <= eol; value++);
3513 if (value > eol) {
3514 throw new IOException("Invalid pax declaration");
3515 }
3516
3517 // pax requires that key/value strings be in UTF-8
3518 String keyStr = new String(data, key, value-key, "UTF-8");
3519 // -1 to strip the trailing LF
3520 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3521
3522 if ("path".equals(keyStr)) {
3523 info.path = valStr;
3524 } else if ("size".equals(keyStr)) {
3525 info.size = Long.parseLong(valStr);
3526 } else {
3527 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3528 }
3529
3530 offset += linelen;
3531 } while (offset < contentSize);
3532
3533 return true;
3534 }
3535
3536 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3537 throws IOException {
3538 long value = 0;
3539 final int end = offset + maxChars;
3540 for (int i = offset; i < end; i++) {
3541 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003542 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003543 if (b == 0 || b == ' ') break;
3544 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003545 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003546 }
3547 value = radix * value + (b - '0');
3548 }
3549 return value;
3550 }
3551
3552 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3553 final int end = offset + maxChars;
3554 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003555 // tar string fields terminate early with a NUL
3556 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003557 return new String(data, offset, eos-offset, "US-ASCII");
3558 }
3559
3560 void sendStartRestore() {
3561 if (mObserver != null) {
3562 try {
3563 mObserver.onStartRestore();
3564 } catch (RemoteException e) {
3565 Slog.w(TAG, "full restore observer went away: startRestore");
3566 mObserver = null;
3567 }
3568 }
3569 }
3570
3571 void sendOnRestorePackage(String name) {
3572 if (mObserver != null) {
3573 try {
3574 // TODO: use a more user-friendly name string
3575 mObserver.onRestorePackage(name);
3576 } catch (RemoteException e) {
3577 Slog.w(TAG, "full restore observer went away: restorePackage");
3578 mObserver = null;
3579 }
3580 }
3581 }
3582
3583 void sendEndRestore() {
3584 if (mObserver != null) {
3585 try {
3586 mObserver.onEndRestore();
3587 } catch (RemoteException e) {
3588 Slog.w(TAG, "full restore observer went away: endRestore");
3589 mObserver = null;
3590 }
3591 }
3592 }
3593 }
3594
Christopher Tatedf01dea2009-06-09 20:45:02 -07003595 // ----- Restore handling -----
3596
Christopher Tate78dd4a72009-11-04 11:49:08 -08003597 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3598 // If the target resides on the system partition, we allow it to restore
3599 // data from the like-named package in a restore set even if the signatures
3600 // do not match. (Unlike general applications, those flashed to the system
3601 // partition will be signed with the device's platform certificate, so on
3602 // different phones the same system app will have different signatures.)
3603 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003604 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003605 return true;
3606 }
3607
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003608 // Allow unsigned apps, but not signed on one device and unsigned on the other
3609 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003610 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003611 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003612 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003613 if ((storedSigs == null || storedSigs.length == 0)
3614 && (deviceSigs == null || deviceSigs.length == 0)) {
3615 return true;
3616 }
3617 if (storedSigs == null || deviceSigs == null) {
3618 return false;
3619 }
3620
Christopher Tateabce4e82009-06-18 18:35:32 -07003621 // !!! TODO: this demands that every stored signature match one
3622 // that is present on device, and does not demand the converse.
3623 // Is this this right policy?
3624 int nStored = storedSigs.length;
3625 int nDevice = deviceSigs.length;
3626
3627 for (int i=0; i < nStored; i++) {
3628 boolean match = false;
3629 for (int j=0; j < nDevice; j++) {
3630 if (storedSigs[i].equals(deviceSigs[j])) {
3631 match = true;
3632 break;
3633 }
3634 }
3635 if (!match) {
3636 return false;
3637 }
3638 }
3639 return true;
3640 }
3641
Christopher Tate44a27902010-01-27 17:15:49 -08003642 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003643 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003644 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003645 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003646 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003647 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003648 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003649 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003650 private HashSet<String> mFilterSet;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003651
Christopher Tate5cbbf562009-06-22 16:44:51 -07003652 class RestoreRequest {
3653 public PackageInfo app;
3654 public int storedAppVersion;
3655
3656 RestoreRequest(PackageInfo _app, int _version) {
3657 app = _app;
3658 storedAppVersion = _version;
3659 }
3660 }
3661
Christopher Tate44a27902010-01-27 17:15:49 -08003662 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003663 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003664 boolean needFullBackup, String[] filterSet) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003665 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003666 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003667 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003668 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003669 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003670 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003671
Christopher Tate284f1bb2011-07-07 14:31:18 -07003672 if (filterSet != null) {
3673 mFilterSet = new HashSet<String>();
3674 for (String pkg : filterSet) {
3675 mFilterSet.add(pkg);
3676 }
3677 } else {
3678 mFilterSet = null;
3679 }
3680
Christopher Tate5cb400b2009-06-25 16:03:14 -07003681 try {
3682 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3683 } catch (RemoteException e) {
3684 // can't happen; the transport is local
3685 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003686 }
3687
Christopher Tatedf01dea2009-06-09 20:45:02 -07003688 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003689 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003690 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08003691 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate284f1bb2011-07-07 14:31:18 -07003692 + " mTargetPackage=" + mTargetPackage + " mFilterSet=" + mFilterSet
3693 + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003694
Christopher Tateb49ceb32010-02-08 16:22:24 -08003695 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003696 int error = -1; // assume error
3697
Dan Egnorefe52642009-06-24 00:16:33 -07003698 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07003699 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003700 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003701 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07003702
Dan Egnorefe52642009-06-24 00:16:33 -07003703 // Get the list of all packages which have backup enabled.
3704 // (Include the Package Manager metadata pseudo-package first.)
3705 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
3706 PackageInfo omPackage = new PackageInfo();
3707 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
3708 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003709
Dan Egnorefe52642009-06-24 00:16:33 -07003710 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003711 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07003712 // if there's a filter set, strip out anything that isn't
3713 // present before proceeding
3714 if (mFilterSet != null) {
3715 for (int i = agentPackages.size() - 1; i >= 0; i--) {
3716 final PackageInfo pkg = agentPackages.get(i);
3717 if (! mFilterSet.contains(pkg.packageName)) {
3718 agentPackages.remove(i);
3719 }
3720 }
3721 if (DEBUG) {
3722 Slog.i(TAG, "Post-filter package set for restore:");
3723 for (PackageInfo p : agentPackages) {
3724 Slog.i(TAG, " " + p);
3725 }
3726 }
3727 }
Christopher Tate84725812010-02-04 15:52:40 -08003728 restorePackages.addAll(agentPackages);
3729 } else {
3730 // Just one package to attempt restore of
3731 restorePackages.add(mTargetPackage);
3732 }
Dan Egnorefe52642009-06-24 00:16:33 -07003733
Christopher Tate7d562ec2009-06-25 18:03:43 -07003734 // let the observer know that we're running
3735 if (mObserver != null) {
3736 try {
3737 // !!! TODO: get an actual count from the transport after
3738 // its startRestore() runs?
3739 mObserver.restoreStarting(restorePackages.size());
3740 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003741 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003742 mObserver = null;
3743 }
3744 }
3745
Dan Egnor01445162009-09-21 17:04:05 -07003746 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
3747 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003748 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003749 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003750 return;
3751 }
3752
3753 String packageName = mTransport.nextRestorePackage();
3754 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003755 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003756 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003757 return;
3758 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003759 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003760 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003761 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07003762 return;
3763 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003764 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07003765 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003766 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003767 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003768 return;
3769 }
3770
3771 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08003772 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07003773 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07003774 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
3775 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07003776
Christopher Tate8c032472009-07-02 14:28:47 -07003777 // Verify that the backup set includes metadata. If not, we can't do
3778 // signature/version verification etc, so we simply do not proceed with
3779 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07003780 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003781 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003782 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003783 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07003784 return;
3785 }
3786
Christopher Tate7d562ec2009-06-25 18:03:43 -07003787 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07003788 for (;;) {
3789 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003790
Dan Egnorefe52642009-06-24 00:16:33 -07003791 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003792 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003793 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003794 return;
3795 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003796 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07003797 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003798 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003799
Christopher Tate7d562ec2009-06-25 18:03:43 -07003800 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07003801 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07003802 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07003803 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003804 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003805 mObserver = null;
3806 }
3807 }
3808
Dan Egnorefe52642009-06-24 00:16:33 -07003809 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
3810 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003811 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003812 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003813 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003814 continue;
3815 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003816
Dan Egnorbb9001c2009-07-27 12:20:13 -07003817 PackageInfo packageInfo;
3818 try {
3819 int flags = PackageManager.GET_SIGNATURES;
3820 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
3821 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003822 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003823 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003824 "Package missing on device");
3825 continue;
3826 }
3827
Dan Egnorefe52642009-06-24 00:16:33 -07003828 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08003829 // Data is from a "newer" version of the app than we have currently
3830 // installed. If the app has not declared that it is prepared to
3831 // handle this case, we do not attempt the restore.
3832 if ((packageInfo.applicationInfo.flags
3833 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
3834 String message = "Version " + metaInfo.versionCode
3835 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003836 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08003837 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
3838 packageName, message);
3839 continue;
3840 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003841 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08003842 + " > installed " + packageInfo.versionCode
3843 + " but restoreAnyVersion");
3844 }
Dan Egnorefe52642009-06-24 00:16:33 -07003845 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003846
Christopher Tate78dd4a72009-11-04 11:49:08 -08003847 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003848 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003849 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003850 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07003851 continue;
3852 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003853
Joe Onorato8a9b2202010-02-26 18:56:32 -08003854 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07003855 + " restore version [" + metaInfo.versionCode
3856 + "] is compatible with installed version ["
3857 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07003858
Christopher Tate3de55bc2010-03-12 17:28:08 -08003859 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07003860 IBackupAgent agent = bindToAgentSynchronous(
3861 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08003862 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07003863 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003864 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003865 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003866 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003867 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003868 }
3869
Christopher Tate5e1ab332009-09-01 20:32:49 -07003870 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07003871 try {
Chris Tate249345b2010-10-29 12:57:04 -07003872 processOneRestore(packageInfo, metaInfo.versionCode, agent,
3873 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003874 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07003875 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003876 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07003877 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07003878
3879 // The agent was probably running with a stub Application object,
3880 // which isn't a valid run mode for the main app logic. Shut
3881 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08003882 // usual full initialization. Note that this is only done for
3883 // full-system restores: when a single app has requested a restore,
3884 // it is explicitly not killed following that operation.
3885 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07003886 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003887 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003888 + packageInfo.applicationInfo.processName);
3889 mActivityManager.killApplicationProcess(
3890 packageInfo.applicationInfo.processName,
3891 packageInfo.applicationInfo.uid);
3892 }
Dan Egnorefe52642009-06-24 00:16:33 -07003893 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003894 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003895
3896 // if we get this far, report success to the observer
3897 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07003898 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003899 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003900 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003901 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003902 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003903 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003904
Dan Egnorefe52642009-06-24 00:16:33 -07003905 try {
3906 mTransport.finishRestore();
3907 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003908 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003909 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003910
3911 if (mObserver != null) {
3912 try {
3913 mObserver.restoreFinished(error);
3914 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003915 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003916 }
3917 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003918
Christopher Tate84725812010-02-04 15:52:40 -08003919 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08003920 // ancestral dataset, as well as the set of apps that are possibly
3921 // restoreable from the dataset
3922 if (mTargetPackage == null && pmAgent != null) {
3923 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003924 mAncestralToken = mToken;
3925 writeRestoreTokens();
3926 }
3927
Christopher Tate1bb69062010-02-19 17:02:12 -08003928 // We must under all circumstances tell the Package Manager to
3929 // proceed with install notifications if it's waiting for us.
3930 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003931 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08003932 try {
3933 mPackageManagerBinder.finishPackageInstall(mPmToken);
3934 } catch (RemoteException e) { /* can't happen */ }
3935 }
3936
Christopher Tate73a3cb32010-12-13 18:27:26 -08003937 // Furthermore we need to reset the session timeout clock
3938 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3939 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
3940 TIMEOUT_RESTORE_INTERVAL);
3941
Christopher Tateb6787f22009-07-02 17:40:45 -07003942 // done; we can finally release the wakelock
3943 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07003944 }
3945 }
3946
Dan Egnorefe52642009-06-24 00:16:33 -07003947 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07003948 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
3949 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003950 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07003951 final String packageName = app.packageName;
3952
Joe Onorato8a9b2202010-02-26 18:56:32 -08003953 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003954
Christopher Tatec7b31e32009-06-10 15:49:30 -07003955 // !!! TODO: get the dirs from the transport
3956 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003957 File newStateName = new File(mStateDir, packageName + ".new");
3958 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003959
Dan Egnorbb9001c2009-07-27 12:20:13 -07003960 ParcelFileDescriptor backupData = null;
3961 ParcelFileDescriptor newState = null;
3962
Christopher Tate4a627c72011-04-01 14:43:32 -07003963 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003964 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07003965 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07003966 backupData = ParcelFileDescriptor.open(backupDataName,
3967 ParcelFileDescriptor.MODE_READ_WRITE |
3968 ParcelFileDescriptor.MODE_CREATE |
3969 ParcelFileDescriptor.MODE_TRUNCATE);
3970
Dan Egnor01445162009-09-21 17:04:05 -07003971 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003972 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003973 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003974 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07003975 }
3976
3977 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07003978 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07003979 backupData = ParcelFileDescriptor.open(backupDataName,
3980 ParcelFileDescriptor.MODE_READ_ONLY);
3981
Dan Egnorbb9001c2009-07-27 12:20:13 -07003982 newState = ParcelFileDescriptor.open(newStateName,
3983 ParcelFileDescriptor.MODE_READ_WRITE |
3984 ParcelFileDescriptor.MODE_CREATE |
3985 ParcelFileDescriptor.MODE_TRUNCATE);
3986
Christopher Tate44a27902010-01-27 17:15:49 -08003987 // Kick off the restore, checking for hung agents
3988 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
3989 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
3990 boolean success = waitUntilOperationComplete(token);
3991
3992 if (!success) {
3993 throw new RuntimeException("restore timeout");
3994 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07003995
3996 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07003997 //
3998 // !!! TODO: the restored data should be migrated on the server
3999 // side into the current dataset. In that case the new state file
4000 // we just created would reflect the data already extant in the
4001 // backend, so there'd be nothing more to do. Until that happens,
4002 // however, we need to make sure that we record the data to the
4003 // current backend dataset. (Yes, this means shipping the data over
4004 // the wire in both directions. That's bad, but consistency comes
4005 // first, then efficiency.) Once we introduce server-side data
4006 // migration to the newly-restored device's dataset, we will change
4007 // the following from a discard of the newly-written state to the
4008 // "correct" operation of renaming into the canonical state blob.
4009 newStateName.delete(); // TODO: remove; see above comment
4010 //newStateName.renameTo(savedStateName); // TODO: replace with this
4011
Dan Egnorbb9001c2009-07-27 12:20:13 -07004012 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004013 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004014 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004015 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004016 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07004017
Christopher Tate96733042009-07-20 14:49:13 -07004018 // If the agent fails restore, it might have put the app's data
4019 // into an incoherent state. For consistency we wipe its data
4020 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07004021 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07004022 } finally {
4023 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004024 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
4025 try { if (newState != null) newState.close(); } catch (IOException e) {}
4026 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07004027 synchronized (mCurrentOperations) {
4028 mCurrentOperations.delete(token);
4029 }
Chris Tate249345b2010-10-29 12:57:04 -07004030
4031 // If we know a priori that we'll need to perform a full post-restore backup
4032 // pass, clear the new state file data. This means we're discarding work that
4033 // was just done by the app's agent, but this way the agent doesn't need to
4034 // take any special action based on global device state.
4035 if (needFullBackup) {
4036 newStateName.delete();
4037 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004038 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004039 }
4040 }
4041
Christopher Tate44a27902010-01-27 17:15:49 -08004042 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004043 IBackupTransport mTransport;
4044 PackageInfo mPackage;
4045
Christopher Tate44a27902010-01-27 17:15:49 -08004046 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004047 mTransport = transport;
4048 mPackage = packageInfo;
4049 }
4050
Christopher Tateee0e78a2009-07-02 11:17:03 -07004051 public void run() {
4052 try {
4053 // Clear the on-device backup state to ensure a full backup next time
4054 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4055 File stateFile = new File(stateDir, mPackage.packageName);
4056 stateFile.delete();
4057
4058 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004059 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004060 mTransport.clearBackupData(mPackage);
4061 } catch (RemoteException e) {
4062 // can't happen; the transport is local
4063 } finally {
4064 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004065 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004066 mTransport.finishBackup();
4067 } catch (RemoteException e) {
4068 // can't happen; the transport is local
4069 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004070
4071 // Last but not least, release the cpu
4072 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004073 }
4074 }
4075 }
4076
Christopher Tate44a27902010-01-27 17:15:49 -08004077 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004078 HashSet<String> mQueue;
4079
Christopher Tate44a27902010-01-27 17:15:49 -08004080 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004081 mQueue = transportNames;
4082 }
4083
Christopher Tate4cc86e12009-09-21 19:36:51 -07004084 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004085 try {
4086 for (String transportName : mQueue) {
4087 IBackupTransport transport = getTransport(transportName);
4088 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004089 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004090 continue;
4091 }
4092
Joe Onorato8a9b2202010-02-26 18:56:32 -08004093 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004094 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004095 long startRealtime = SystemClock.elapsedRealtime();
4096 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004097
Christopher Tate4cc86e12009-09-21 19:36:51 -07004098 if (status == BackupConstants.TRANSPORT_OK) {
4099 status = transport.finishBackup();
4100 }
4101
4102 // Okay, the wipe really happened. Clean up our local bookkeeping.
4103 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004104 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004105 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004106 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004107 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004108 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004109 synchronized (mQueueLock) {
4110 recordInitPendingLocked(false, transportName);
4111 }
Dan Egnor726247c2009-09-29 19:12:31 -07004112 } else {
4113 // If this didn't work, requeue this one and try again
4114 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004115 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004116 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004117 synchronized (mQueueLock) {
4118 recordInitPendingLocked(true, transportName);
4119 }
4120 // do this via another alarm to make sure of the wakelock states
4121 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004122 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004123 + transportName + " resched in " + delay);
4124 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4125 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004126 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004127 }
4128 } catch (RemoteException e) {
4129 // can't happen; the transports are local
4130 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004131 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004132 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004133 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004134 mWakelock.release();
4135 }
4136 }
4137 }
4138
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004139 private void dataChangedImpl(String packageName) {
4140 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4141 dataChangedImpl(packageName, targets);
4142 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004143
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004144 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004145 // Record that we need a backup pass for the caller. Since multiple callers
4146 // may share a uid, we need to note all candidates within that uid and schedule
4147 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004148 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004149
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004150 if (targets == null) {
4151 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4152 + " uid=" + Binder.getCallingUid());
4153 return;
4154 }
4155
4156 synchronized (mQueueLock) {
4157 // Note that this client has made data changes that need to be backed up
4158 for (ApplicationInfo app : targets) {
4159 // validate the caller-supplied package name against the known set of
4160 // packages associated with this uid
4161 if (app.packageName.equals(packageName)) {
4162 // Add the caller to the set of pending backups. If there is
4163 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07004164 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08004165 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004166 // Journal this request in case of crash. The put()
4167 // operation returned null when this package was not already
4168 // in the set; we want to avoid touching the disk redundantly.
4169 writeToJournalLocked(packageName);
4170
4171 if (DEBUG) {
4172 int numKeys = mPendingBackups.size();
4173 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4174 for (BackupRequest b : mPendingBackups.values()) {
4175 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
4176 }
4177 }
4178 }
4179 }
4180 }
4181 }
4182 }
4183
4184 // Note: packageName is currently unused, but may be in the future
4185 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004186 // If the caller does not hold the BACKUP permission, it can only request a
4187 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004188 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004189 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004190 synchronized (mBackupParticipants) {
4191 return mBackupParticipants.get(Binder.getCallingUid());
4192 }
4193 }
4194
4195 // a caller with full permission can ask to back up any participating app
4196 // !!! TODO: allow backup of ANY app?
4197 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4198 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004199 int N = mBackupParticipants.size();
4200 for (int i = 0; i < N; i++) {
4201 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4202 if (s != null) {
4203 targets.addAll(s);
4204 }
4205 }
4206 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004207 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004208 }
Christopher Tate46758122009-05-06 11:22:00 -07004209
Christopher Tatecde87f42009-06-12 12:55:53 -07004210 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004211 RandomAccessFile out = null;
4212 try {
4213 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4214 out = new RandomAccessFile(mJournal, "rws");
4215 out.seek(out.length());
4216 out.writeUTF(str);
4217 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004218 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004219 mJournal = null;
4220 } finally {
4221 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004222 }
4223 }
4224
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004225 // ----- IBackupManager binder interface -----
4226
4227 public void dataChanged(final String packageName) {
4228 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4229 if (targets == null) {
4230 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4231 + " uid=" + Binder.getCallingUid());
4232 return;
4233 }
4234
4235 mBackupHandler.post(new Runnable() {
4236 public void run() {
4237 dataChangedImpl(packageName, targets);
4238 }
4239 });
4240 }
4241
Christopher Tateee0e78a2009-07-02 11:17:03 -07004242 // Clear the given package's backup data from the current transport
4243 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004244 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004245 PackageInfo info;
4246 try {
4247 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4248 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004249 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004250 return;
4251 }
4252
4253 // If the caller does not hold the BACKUP permission, it can only request a
4254 // wipe of its own backed-up data.
4255 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004256 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004257 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4258 apps = mBackupParticipants.get(Binder.getCallingUid());
4259 } else {
4260 // a caller with full permission can ask to back up any participating app
4261 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004262 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004263 apps = new HashSet<ApplicationInfo>();
4264 int N = mBackupParticipants.size();
4265 for (int i = 0; i < N; i++) {
4266 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4267 if (s != null) {
4268 apps.addAll(s);
4269 }
4270 }
4271 }
4272
4273 // now find the given package in the set of candidate apps
4274 for (ApplicationInfo app : apps) {
4275 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004276 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004277 // found it; fire off the clear request
4278 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004279 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004280 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004281 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4282 new ClearParams(getTransport(mCurrentTransport), info));
4283 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004284 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004285 }
4286 break;
4287 }
4288 }
4289 }
4290
Christopher Tateace7f092009-06-15 18:07:25 -07004291 // Run a backup pass immediately for any applications that have declared
4292 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004293 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004294 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004295
Joe Onorato8a9b2202010-02-26 18:56:32 -08004296 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004297 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004298 // Because the alarms we are using can jitter, and we want an *immediate*
4299 // backup pass to happen, we restart the timer beginning with "next time,"
4300 // then manually fire the backup trigger intent ourselves.
4301 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004302 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004303 mRunBackupIntent.send();
4304 } catch (PendingIntent.CanceledException e) {
4305 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004306 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004307 }
Christopher Tate46758122009-05-06 11:22:00 -07004308 }
4309 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004310
Christopher Tate4a627c72011-04-01 14:43:32 -07004311 // Run a *full* backup pass for the given package, writing the resulting data stream
4312 // to the supplied file descriptor. This method is synchronous and does not return
4313 // to the caller until the backup has been completed.
4314 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4315 boolean doAllApps, String[] pkgList) {
4316 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4317
4318 // Validate
4319 if (!doAllApps) {
4320 if (!includeShared) {
4321 // If we're backing up shared data (sdcard or equivalent), then we can run
4322 // without any supplied app names. Otherwise, we'd be doing no work, so
4323 // report the error.
4324 if (pkgList == null || pkgList.length == 0) {
4325 throw new IllegalArgumentException(
4326 "Backup requested but neither shared nor any apps named");
4327 }
4328 }
4329 }
4330
4331 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4332 + " shared=" + includeShared + " all=" + doAllApps
4333 + " pkgs=" + pkgList);
4334
4335 long oldId = Binder.clearCallingIdentity();
4336 try {
4337 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4338 doAllApps, pkgList);
4339 final int token = generateToken();
4340 synchronized (mFullConfirmations) {
4341 mFullConfirmations.put(token, params);
4342 }
4343
Christopher Tate75a99702011-05-18 16:28:19 -07004344 // start up the confirmation UI
4345 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4346 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4347 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004348 mFullConfirmations.delete(token);
4349 return;
4350 }
Christopher Tate75a99702011-05-18 16:28:19 -07004351
4352 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004353 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4354
4355 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004356 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004357
4358 // wait for the backup to be performed
4359 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4360 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004361 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004362 try {
4363 fd.close();
4364 } catch (IOException e) {
4365 // just eat it
4366 }
Christopher Tate75a99702011-05-18 16:28:19 -07004367 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07004368 }
Christopher Tate75a99702011-05-18 16:28:19 -07004369 if (DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
4370 }
4371
4372 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004373 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004374 Slog.i(TAG, "Beginning full restore...");
4375
4376 long oldId = Binder.clearCallingIdentity();
4377
4378 try {
4379 FullRestoreParams params = new FullRestoreParams(fd);
4380 final int token = generateToken();
4381 synchronized (mFullConfirmations) {
4382 mFullConfirmations.put(token, params);
4383 }
4384
4385 // start up the confirmation UI
4386 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4387 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4388 Slog.e(TAG, "Unable to launch full restore confirmation");
4389 mFullConfirmations.delete(token);
4390 return;
4391 }
4392
4393 // make sure the screen is lit for the user interaction
4394 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4395
4396 // start the confirmation countdown
4397 startConfirmationTimeout(token, params);
4398
4399 // wait for the restore to be performed
4400 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4401 waitForCompletion(params);
4402 } finally {
4403 try {
4404 fd.close();
4405 } catch (IOException e) {
4406 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4407 }
4408 Binder.restoreCallingIdentity(oldId);
4409 Slog.i(TAG, "Full restore completed");
4410 }
4411 }
4412
4413 boolean startConfirmationUi(int token, String action) {
4414 try {
4415 Intent confIntent = new Intent(action);
4416 confIntent.setClassName("com.android.backupconfirm",
4417 "com.android.backupconfirm.BackupRestoreConfirmation");
4418 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4419 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4420 mContext.startActivity(confIntent);
4421 } catch (ActivityNotFoundException e) {
4422 return false;
4423 }
4424 return true;
4425 }
4426
4427 void startConfirmationTimeout(int token, FullParams params) {
4428 if (DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
4429 + TIMEOUT_FULL_CONFIRMATION + " millis");
4430 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4431 token, 0, params);
4432 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004433 }
4434
4435 void waitForCompletion(FullParams params) {
4436 synchronized (params.latch) {
4437 while (params.latch.get() == false) {
4438 try {
4439 params.latch.wait();
4440 } catch (InterruptedException e) { /* never interrupted */ }
4441 }
4442 }
4443 }
4444
4445 void signalFullBackupRestoreCompletion(FullParams params) {
4446 synchronized (params.latch) {
4447 params.latch.set(true);
4448 params.latch.notifyAll();
4449 }
4450 }
4451
4452 // Confirm that the previously-requested full backup/restore operation can proceed. This
4453 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004454 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004455 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004456 String password, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004457 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4458 + " allow=" + allow);
4459
4460 // TODO: possibly require not just this signature-only permission, but even
4461 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004462 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004463
4464 long oldId = Binder.clearCallingIdentity();
4465 try {
4466
4467 FullParams params;
4468 synchronized (mFullConfirmations) {
4469 params = mFullConfirmations.get(token);
4470 if (params != null) {
4471 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4472 mFullConfirmations.delete(token);
4473
4474 if (allow) {
4475 params.observer = observer;
Christopher Tate2efd2db2011-07-19 16:32:49 -07004476 params.password = password;
Christopher Tate4a627c72011-04-01 14:43:32 -07004477 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004478 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004479 : MSG_RUN_FULL_RESTORE;
4480
Christopher Tate75a99702011-05-18 16:28:19 -07004481 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004482 mWakelock.acquire();
4483 Message msg = mBackupHandler.obtainMessage(verb, params);
4484 mBackupHandler.sendMessage(msg);
4485 } else {
4486 Slog.w(TAG, "User rejected full backup/restore operation");
4487 // indicate completion without having actually transferred any data
4488 signalFullBackupRestoreCompletion(params);
4489 }
4490 } else {
4491 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4492 }
4493 }
4494 } finally {
4495 Binder.restoreCallingIdentity(oldId);
4496 }
4497 }
4498
Christopher Tate8031a3d2009-07-06 16:36:05 -07004499 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004500 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004501 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004502 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004503
Joe Onorato8a9b2202010-02-26 18:56:32 -08004504 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004505
Christopher Tate6ef58a12009-06-29 14:56:28 -07004506 boolean wasEnabled = mEnabled;
4507 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004508 Settings.Secure.putInt(mContext.getContentResolver(),
4509 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004510 mEnabled = enable;
4511 }
4512
Christopher Tate49401dd2009-07-01 12:34:29 -07004513 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004514 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004515 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004516 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004517 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004518 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004519 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004520
Christopher Tateb6787f22009-07-02 17:40:45 -07004521 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004522
4523 // This also constitutes an opt-out, so we wipe any data for
4524 // this device from the backend. We start that process with
4525 // an alarm in order to guarantee wakelock states.
4526 if (wasEnabled && mProvisioned) {
4527 // NOTE: we currently flush every registered transport, not just
4528 // the currently-active one.
4529 HashSet<String> allTransports;
4530 synchronized (mTransports) {
4531 allTransports = new HashSet<String>(mTransports.keySet());
4532 }
4533 // build the set of transports for which we are posting an init
4534 for (String transport : allTransports) {
4535 recordInitPendingLocked(true, transport);
4536 }
4537 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4538 mRunInitIntent);
4539 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004540 }
4541 }
Christopher Tate49401dd2009-07-01 12:34:29 -07004542 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004543
Christopher Tatecce9da52010-02-03 15:11:15 -08004544 // Enable/disable automatic restore of app data at install time
4545 public void setAutoRestore(boolean doAutoRestore) {
4546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004547 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08004548
Joe Onorato8a9b2202010-02-26 18:56:32 -08004549 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08004550
4551 synchronized (this) {
4552 Settings.Secure.putInt(mContext.getContentResolver(),
4553 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
4554 mAutoRestore = doAutoRestore;
4555 }
4556 }
4557
Christopher Tate8031a3d2009-07-06 16:36:05 -07004558 // Mark the backup service as having been provisioned
4559 public void setBackupProvisioned(boolean available) {
4560 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4561 "setBackupProvisioned");
4562
4563 boolean wasProvisioned = mProvisioned;
4564 synchronized (this) {
4565 Settings.Secure.putInt(mContext.getContentResolver(),
4566 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
4567 mProvisioned = available;
4568 }
4569
4570 synchronized (mQueueLock) {
4571 if (available && !wasProvisioned && mEnabled) {
4572 // we're now good to go, so start the backup alarms
4573 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
4574 } else if (!available) {
4575 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004576 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07004577 mAlarmManager.cancel(mRunBackupIntent);
4578 }
4579 }
4580 }
4581
4582 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07004583 // We used to use setInexactRepeating(), but that may be linked to
4584 // backups running at :00 more often than not, creating load spikes.
4585 // Schedule at an exact time for now, and also add a bit of "fuzz".
4586
4587 Random random = new Random();
4588 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
4589 random.nextInt(FUZZ_MILLIS);
4590 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
4591 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07004592 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07004593 }
4594
Christopher Tate6ef58a12009-06-29 14:56:28 -07004595 // Report whether the backup mechanism is currently enabled
4596 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04004597 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004598 return mEnabled; // no need to synchronize just to read it
4599 }
4600
Christopher Tate91717492009-06-26 21:07:13 -07004601 // Report the name of the currently active transport
4602 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04004603 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004604 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08004605 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07004606 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07004607 }
4608
Christopher Tate91717492009-06-26 21:07:13 -07004609 // Report all known, available backup transports
4610 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07004611 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07004612
Christopher Tate91717492009-06-26 21:07:13 -07004613 String[] list = null;
4614 ArrayList<String> known = new ArrayList<String>();
4615 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
4616 if (entry.getValue() != null) {
4617 known.add(entry.getKey());
4618 }
4619 }
4620
4621 if (known.size() > 0) {
4622 list = new String[known.size()];
4623 known.toArray(list);
4624 }
4625 return list;
4626 }
4627
4628 // Select which transport to use for the next backup operation. If the given
4629 // name is not one of the available transports, no action is taken and the method
4630 // returns null.
4631 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04004632 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07004633
4634 synchronized (mTransports) {
4635 String prevTransport = null;
4636 if (mTransports.get(transport) != null) {
4637 prevTransport = mCurrentTransport;
4638 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07004639 Settings.Secure.putString(mContext.getContentResolver(),
4640 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004641 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07004642 + " returning " + prevTransport);
4643 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004644 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07004645 }
4646 return prevTransport;
4647 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004648 }
4649
Christopher Tatef5e1c292010-12-08 18:40:26 -08004650 // Supply the configuration Intent for the given transport. If the name is not one
4651 // of the available transports, or if the transport does not supply any configuration
4652 // UI, the method returns null.
4653 public Intent getConfigurationIntent(String transportName) {
4654 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4655 "getConfigurationIntent");
4656
4657 synchronized (mTransports) {
4658 final IBackupTransport transport = mTransports.get(transportName);
4659 if (transport != null) {
4660 try {
4661 final Intent intent = transport.configurationIntent();
4662 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
4663 + intent);
4664 return intent;
4665 } catch (RemoteException e) {
4666 /* fall through to return null */
4667 }
4668 }
4669 }
4670
4671 return null;
4672 }
4673
4674 // Supply the configuration summary string for the given transport. If the name is
4675 // not one of the available transports, or if the transport does not supply any
4676 // summary / destination string, the method can return null.
4677 //
4678 // This string is used VERBATIM as the summary text of the relevant Settings item!
4679 public String getDestinationString(String transportName) {
4680 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004681 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08004682
4683 synchronized (mTransports) {
4684 final IBackupTransport transport = mTransports.get(transportName);
4685 if (transport != null) {
4686 try {
4687 final String text = transport.currentDestinationString();
4688 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
4689 return text;
4690 } catch (RemoteException e) {
4691 /* fall through to return null */
4692 }
4693 }
4694 }
4695
4696 return null;
4697 }
4698
Christopher Tate043dadc2009-06-02 16:11:00 -07004699 // Callback: a requested backup agent has been instantiated. This should only
4700 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004701 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07004702 synchronized(mAgentConnectLock) {
4703 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004704 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07004705 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
4706 mConnectedAgent = agent;
4707 mConnecting = false;
4708 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004709 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004710 + " claiming agent connected");
4711 }
4712 mAgentConnectLock.notifyAll();
4713 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004714 }
4715
4716 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
4717 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07004718 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004719 public void agentDisconnected(String packageName) {
4720 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07004721 synchronized(mAgentConnectLock) {
4722 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
4723 mConnectedAgent = null;
4724 mConnecting = false;
4725 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004726 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004727 + " claiming agent disconnected");
4728 }
4729 mAgentConnectLock.notifyAll();
4730 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004731 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004732
Christopher Tate1bb69062010-02-19 17:02:12 -08004733 // An application being installed will need a restore pass, then the Package Manager
4734 // will need to be told when the restore is finished.
4735 public void restoreAtInstall(String packageName, int token) {
4736 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004737 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08004738 + " attemping install-time restore");
4739 return;
4740 }
4741
4742 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004743 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08004744 + " token=" + Integer.toHexString(token));
4745
Christopher Tatef0872722010-02-25 15:22:48 -08004746 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08004747 // okay, we're going to attempt a restore of this package from this restore set.
4748 // The eventual message back into the Package Manager to run the post-install
4749 // steps for 'token' will be issued from the restore handling code.
4750
4751 // We can use a synthetic PackageInfo here because:
4752 // 1. We know it's valid, since the Package Manager supplied the name
4753 // 2. Only the packageName field will be used by the restore code
4754 PackageInfo pkg = new PackageInfo();
4755 pkg.packageName = packageName;
4756
4757 mWakelock.acquire();
4758 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4759 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07004760 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08004761 mBackupHandler.sendMessage(msg);
4762 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08004763 // Auto-restore disabled or no way to attempt a restore; just tell the Package
4764 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004765 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08004766 try {
4767 mPackageManagerBinder.finishPackageInstall(token);
4768 } catch (RemoteException e) { /* can't happen */ }
4769 }
4770 }
4771
Christopher Tate8c850b72009-06-07 19:33:20 -07004772 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08004773 public IRestoreSession beginRestoreSession(String packageName, String transport) {
4774 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
4775 + " transport=" + transport);
4776
4777 boolean needPermission = true;
4778 if (transport == null) {
4779 transport = mCurrentTransport;
4780
4781 if (packageName != null) {
4782 PackageInfo app = null;
4783 try {
4784 app = mPackageManager.getPackageInfo(packageName, 0);
4785 } catch (NameNotFoundException nnf) {
4786 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
4787 throw new IllegalArgumentException("Package " + packageName + " not found");
4788 }
4789
4790 if (app.applicationInfo.uid == Binder.getCallingUid()) {
4791 // So: using the current active transport, and the caller has asked
4792 // that its own package will be restored. In this narrow use case
4793 // we do not require the caller to hold the permission.
4794 needPermission = false;
4795 }
4796 }
4797 }
4798
4799 if (needPermission) {
4800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4801 "beginRestoreSession");
4802 } else {
4803 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
4804 }
Christopher Tatef68eb502009-06-16 11:02:01 -07004805
4806 synchronized(this) {
4807 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004808 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07004809 return null;
4810 }
Chris Tate44ab8452010-11-16 15:10:49 -08004811 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08004812 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07004813 }
4814 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07004815 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004816
Christopher Tate73a3cb32010-12-13 18:27:26 -08004817 void clearRestoreSession(ActiveRestoreSession currentSession) {
4818 synchronized(this) {
4819 if (currentSession != mActiveRestoreSession) {
4820 Slog.e(TAG, "ending non-current restore session");
4821 } else {
4822 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
4823 mActiveRestoreSession = null;
4824 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4825 }
4826 }
4827 }
4828
Christopher Tate44a27902010-01-27 17:15:49 -08004829 // Note that a currently-active backup agent has notified us that it has
4830 // completed the given outstanding asynchronous backup/restore operation.
4831 public void opComplete(int token) {
4832 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004833 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08004834 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
4835 mCurrentOpLock.notifyAll();
4836 }
4837 }
4838
Christopher Tate9b3905c2009-06-08 15:24:01 -07004839 // ----- Restore session -----
4840
Christopher Tate80202c82010-01-25 19:37:47 -08004841 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07004842 private static final String TAG = "RestoreSession";
4843
Chris Tate44ab8452010-11-16 15:10:49 -08004844 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004845 private IBackupTransport mRestoreTransport = null;
4846 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08004847 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004848
Chris Tate44ab8452010-11-16 15:10:49 -08004849 ActiveRestoreSession(String packageName, String transport) {
4850 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07004851 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07004852 }
4853
4854 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07004855 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04004856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004857 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004858 if (observer == null) {
4859 throw new IllegalArgumentException("Observer must not be null");
4860 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004861
Christopher Tate73a3cb32010-12-13 18:27:26 -08004862 if (mEnded) {
4863 throw new IllegalStateException("Restore session already ended");
4864 }
4865
Christopher Tate1bb69062010-02-19 17:02:12 -08004866 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07004867 try {
Christopher Tate43383042009-07-13 15:17:13 -07004868 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004869 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004870 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07004871 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07004872 // spin off the transport request to our service thread
4873 mWakelock.acquire();
4874 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
4875 new RestoreGetSetsParams(mRestoreTransport, this, observer));
4876 mBackupHandler.sendMessage(msg);
4877 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07004878 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004879 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07004880 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08004881 } finally {
4882 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07004883 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07004884 }
4885
Christopher Tate84725812010-02-04 15:52:40 -08004886 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07004887 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4888 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004889
Chris Tate44ab8452010-11-16 15:10:49 -08004890 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07004891 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004892
Christopher Tate73a3cb32010-12-13 18:27:26 -08004893 if (mEnded) {
4894 throw new IllegalStateException("Restore session already ended");
4895 }
4896
Dan Egnor0084da52009-07-29 12:57:16 -07004897 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08004898 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4899 return -1;
4900 }
4901
4902 if (mPackageName != null) {
4903 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07004904 return -1;
4905 }
4906
Christopher Tate21ab6a52009-09-24 18:01:46 -07004907 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004908 for (int i = 0; i < mRestoreSets.length; i++) {
4909 if (token == mRestoreSets[i].token) {
4910 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07004911 mWakelock.acquire();
4912 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004913 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07004914 mBackupHandler.sendMessage(msg);
4915 Binder.restoreCallingIdentity(oldId);
4916 return 0;
4917 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004918 }
4919 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07004920
Joe Onorato8a9b2202010-02-26 18:56:32 -08004921 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07004922 return -1;
4923 }
4924
Christopher Tate284f1bb2011-07-07 14:31:18 -07004925 public synchronized int restoreSome(long token, IRestoreObserver observer,
4926 String[] packages) {
4927 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4928 "performRestore");
4929
4930 if (DEBUG) {
4931 StringBuilder b = new StringBuilder(128);
4932 b.append("restoreSome token=");
4933 b.append(Long.toHexString(token));
4934 b.append(" observer=");
4935 b.append(observer.toString());
4936 b.append(" packages=");
4937 if (packages == null) {
4938 b.append("null");
4939 } else {
4940 b.append('{');
4941 boolean first = true;
4942 for (String s : packages) {
4943 if (!first) {
4944 b.append(", ");
4945 } else first = false;
4946 b.append(s);
4947 }
4948 b.append('}');
4949 }
4950 Slog.d(TAG, b.toString());
4951 }
4952
4953 if (mEnded) {
4954 throw new IllegalStateException("Restore session already ended");
4955 }
4956
4957 if (mRestoreTransport == null || mRestoreSets == null) {
4958 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4959 return -1;
4960 }
4961
4962 if (mPackageName != null) {
4963 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
4964 return -1;
4965 }
4966
4967 synchronized (mQueueLock) {
4968 for (int i = 0; i < mRestoreSets.length; i++) {
4969 if (token == mRestoreSets[i].token) {
4970 long oldId = Binder.clearCallingIdentity();
4971 mWakelock.acquire();
4972 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4973 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
4974 packages, true);
4975 mBackupHandler.sendMessage(msg);
4976 Binder.restoreCallingIdentity(oldId);
4977 return 0;
4978 }
4979 }
4980 }
4981
4982 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
4983 return -1;
4984 }
4985
Christopher Tate84725812010-02-04 15:52:40 -08004986 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004987 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08004988
Christopher Tate73a3cb32010-12-13 18:27:26 -08004989 if (mEnded) {
4990 throw new IllegalStateException("Restore session already ended");
4991 }
4992
Chris Tate44ab8452010-11-16 15:10:49 -08004993 if (mPackageName != null) {
4994 if (! mPackageName.equals(packageName)) {
4995 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
4996 + " on session for package " + mPackageName);
4997 return -1;
4998 }
4999 }
5000
Christopher Tate84725812010-02-04 15:52:40 -08005001 PackageInfo app = null;
5002 try {
5003 app = mPackageManager.getPackageInfo(packageName, 0);
5004 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005005 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005006 return -1;
5007 }
5008
5009 // If the caller is not privileged and is not coming from the target
5010 // app's uid, throw a permission exception back to the caller.
5011 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5012 Binder.getCallingPid(), Binder.getCallingUid());
5013 if ((perm == PackageManager.PERMISSION_DENIED) &&
5014 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005015 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005016 + " or calling uid=" + Binder.getCallingUid());
5017 throw new SecurityException("No permission to restore other packages");
5018 }
5019
Christopher Tate7d411a32010-02-26 11:27:08 -08005020 // If the package has no backup agent, we obviously cannot proceed
5021 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005022 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005023 return -1;
5024 }
5025
Christopher Tate84725812010-02-04 15:52:40 -08005026 // So far so good; we're allowed to try to restore this package. Now
5027 // check whether there is data for it in the current dataset, falling back
5028 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005029 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005030
5031 // If we didn't come up with a place to look -- no ancestral dataset and
5032 // the app has never been backed up from this device -- there's nothing
5033 // to do but return failure.
5034 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005035 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005036 return -1;
5037 }
5038
5039 // Ready to go: enqueue the restore request and claim success
5040 long oldId = Binder.clearCallingIdentity();
5041 mWakelock.acquire();
5042 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005043 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005044 mBackupHandler.sendMessage(msg);
5045 Binder.restoreCallingIdentity(oldId);
5046 return 0;
5047 }
5048
Christopher Tate73a3cb32010-12-13 18:27:26 -08005049 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5050 class EndRestoreRunnable implements Runnable {
5051 BackupManagerService mBackupManager;
5052 ActiveRestoreSession mSession;
5053
5054 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5055 mBackupManager = manager;
5056 mSession = session;
5057 }
5058
5059 public void run() {
5060 // clean up the session's bookkeeping
5061 synchronized (mSession) {
5062 try {
5063 if (mSession.mRestoreTransport != null) {
5064 mSession.mRestoreTransport.finishRestore();
5065 }
5066 } catch (Exception e) {
5067 Slog.e(TAG, "Error in finishRestore", e);
5068 } finally {
5069 mSession.mRestoreTransport = null;
5070 mSession.mEnded = true;
5071 }
5072 }
5073
5074 // clean up the BackupManagerService side of the bookkeeping
5075 // and cancel any pending timeout message
5076 mBackupManager.clearRestoreSession(mSession);
5077 }
5078 }
5079
Dan Egnor0084da52009-07-29 12:57:16 -07005080 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005081 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005082
Christopher Tate73a3cb32010-12-13 18:27:26 -08005083 if (mEnded) {
5084 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005085 }
5086
Christopher Tate73a3cb32010-12-13 18:27:26 -08005087 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005088 }
5089 }
5090
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005091 @Override
5092 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005093 long identityToken = Binder.clearCallingIdentity();
5094 try {
5095 dumpInternal(pw);
5096 } finally {
5097 Binder.restoreCallingIdentity(identityToken);
5098 }
5099 }
5100
5101 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005102 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005103 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005104 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005105 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005106 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005107 pw.println("Last backup pass: " + mLastBackupPass
5108 + " (now = " + System.currentTimeMillis() + ')');
5109 pw.println(" next scheduled: " + mNextBackupPass);
5110
Christopher Tate91717492009-06-26 21:07:13 -07005111 pw.println("Available transports:");
5112 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005113 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5114 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005115 IBackupTransport transport = getTransport(t);
5116 File dir = new File(mBaseStateDir, transport.transportDirName());
5117 pw.println(" destination: " + transport.currentDestinationString());
5118 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005119 for (File f : dir.listFiles()) {
5120 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5121 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005122 } catch (Exception e) {
5123 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005124 pw.println(" Error: " + e);
5125 }
Christopher Tate91717492009-06-26 21:07:13 -07005126 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005127
5128 pw.println("Pending init: " + mPendingInits.size());
5129 for (String s : mPendingInits) {
5130 pw.println(" " + s);
5131 }
5132
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005133 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005134 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005135 for (int i=0; i<N; i++) {
5136 int uid = mBackupParticipants.keyAt(i);
5137 pw.print(" uid: ");
5138 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005139 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5140 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005141 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005142 }
5143 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005144
Christopher Tateb49ceb32010-02-08 16:22:24 -08005145 pw.println("Ancestral packages: "
5146 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005147 if (mAncestralPackages != null) {
5148 for (String pkg : mAncestralPackages) {
5149 pw.println(" " + pkg);
5150 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005151 }
5152
Christopher Tate73e02522009-07-15 14:18:26 -07005153 pw.println("Ever backed up: " + mEverStoredApps.size());
5154 for (String pkg : mEverStoredApps) {
5155 pw.println(" " + pkg);
5156 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005157
5158 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005159 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005160 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005161 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005162 }
5163 }
Christopher Tate487529a2009-04-29 14:03:25 -07005164}