blob: bdd89383ac3afd2c48a4244143b2c618e739dbad [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 Tate728a1c42011-07-28 18:03:03 -0700310 public String curPassword; // filled in by the confirmation step
311 public String encryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -0700312
313 FullParams() {
314 latch = new AtomicBoolean(false);
315 }
316 }
317
318 class FullBackupParams extends FullParams {
319 public boolean includeApks;
320 public boolean includeShared;
321 public boolean allApps;
322 public String[] packages;
323
324 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
325 boolean doAllApps, String[] pkgList) {
326 fd = output;
327 includeApks = saveApks;
328 includeShared = saveShared;
329 allApps = doAllApps;
330 packages = pkgList;
331 }
332 }
333
334 class FullRestoreParams extends FullParams {
335 FullRestoreParams(ParcelFileDescriptor input) {
336 fd = input;
337 }
338 }
339
Christopher Tate44a27902010-01-27 17:15:49 -0800340 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
341 // token is the index of the entry in the pending-operations list.
342 static final int OP_PENDING = 0;
343 static final int OP_ACKNOWLEDGED = 1;
344 static final int OP_TIMEOUT = -1;
345
346 final SparseIntArray mCurrentOperations = new SparseIntArray();
347 final Object mCurrentOpLock = new Object();
348 final Random mTokenGenerator = new Random();
349
Christopher Tate4a627c72011-04-01 14:43:32 -0700350 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
351
Christopher Tate5cb400b2009-06-25 16:03:14 -0700352 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700353 File mBaseStateDir;
354 File mDataDir;
355 File mJournalDir;
356 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700357
Christopher Tate2efd2db2011-07-19 16:32:49 -0700358 // Backup password, if any, and the file where it's saved. What is stored is not the
359 // password text itself; it's the result of a PBKDF2 hash with a randomly chosen (but
360 // persisted) salt. Validation is performed by running the challenge text through the
361 // same PBKDF2 cycle with the persisted salt; if the resulting derived key string matches
362 // the saved hash string, then the challenge text matches the originally supplied
363 // password text.
364 private final SecureRandom mRng = new SecureRandom();
365 private String mPasswordHash;
366 private File mPasswordHashFile;
367 private byte[] mPasswordSalt;
368
369 // Configuration of PBKDF2 that we use for generating pw hashes and intermediate keys
370 static final int PBKDF2_HASH_ROUNDS = 10000;
371 static final int PBKDF2_KEY_SIZE = 256; // bits
372 static final int PBKDF2_SALT_SIZE = 512; // bits
373 static final String ENCRYPTION_ALGORITHM_NAME = "AES-256";
374
Christopher Tate84725812010-02-04 15:52:40 -0800375 // Keep a log of all the apps we've ever backed up, and what the
376 // dataset tokens are for both the current backup dataset and
377 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700378 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700379 HashSet<String> mEverStoredApps = new HashSet<String>();
380
Christopher Tateb49ceb32010-02-08 16:22:24 -0800381 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800382 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800383 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800384 long mAncestralToken = 0;
385 long mCurrentToken = 0;
386
Christopher Tate4cc86e12009-09-21 19:36:51 -0700387 // Persistently track the need to do a full init
388 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
389 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700390
Christopher Tate4a627c72011-04-01 14:43:32 -0700391 // Utility: build a new random integer token
392 int generateToken() {
393 int token;
394 do {
395 synchronized (mTokenGenerator) {
396 token = mTokenGenerator.nextInt();
397 }
398 } while (token < 0);
399 return token;
400 }
401
Christopher Tate44a27902010-01-27 17:15:49 -0800402 // ----- Asynchronous backup/restore handler thread -----
403
404 private class BackupHandler extends Handler {
405 public BackupHandler(Looper looper) {
406 super(looper);
407 }
408
409 public void handleMessage(Message msg) {
410
411 switch (msg.what) {
412 case MSG_RUN_BACKUP:
413 {
414 mLastBackupPass = System.currentTimeMillis();
415 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
416
417 IBackupTransport transport = getTransport(mCurrentTransport);
418 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800419 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800420 mWakelock.release();
421 break;
422 }
423
424 // snapshot the pending-backup set and work on that
425 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800426 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800427 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800428 // Do we have any work to do? Construct the work queue
429 // then release the synchronization lock to actually run
430 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800431 if (mPendingBackups.size() > 0) {
432 for (BackupRequest b: mPendingBackups.values()) {
433 queue.add(b);
434 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800435 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800436 mPendingBackups.clear();
437
438 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800439 mJournal = null;
440
Christopher Tate44a27902010-01-27 17:15:49 -0800441 }
442 }
Christopher Tatec61da312010-02-05 10:41:27 -0800443
444 if (queue.size() > 0) {
445 // At this point, we have started a new journal file, and the old
446 // file identity is being passed to the backup processing thread.
447 // When it completes successfully, that old journal file will be
448 // deleted. If we crash prior to that, the old journal is parsed
449 // at next boot and the journaled requests fulfilled.
450 (new PerformBackupTask(transport, queue, oldJournal)).run();
451 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800452 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800453 mWakelock.release();
454 }
Christopher Tate44a27902010-01-27 17:15:49 -0800455 break;
456 }
457
458 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700459 {
460 FullBackupParams params = (FullBackupParams)msg.obj;
461 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
Christopher Tate728a1c42011-07-28 18:03:03 -0700462 params.includeShared, params.curPassword, params.encryptPassword,
463 params.allApps, params.packages, params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800464 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700465 }
Christopher Tate44a27902010-01-27 17:15:49 -0800466
467 case MSG_RUN_RESTORE:
468 {
469 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800470 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800471 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700472 params.token, params.pkgInfo, params.pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -0700473 params.needFullBackup, params.filterSet)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800474 break;
475 }
476
Christopher Tate75a99702011-05-18 16:28:19 -0700477 case MSG_RUN_FULL_RESTORE:
478 {
479 FullRestoreParams params = (FullRestoreParams)msg.obj;
Christopher Tate728a1c42011-07-28 18:03:03 -0700480 (new PerformFullRestoreTask(params.fd, params.curPassword, params.encryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -0700481 params.observer, params.latch)).run();
Christopher Tate75a99702011-05-18 16:28:19 -0700482 break;
483 }
484
Christopher Tate44a27902010-01-27 17:15:49 -0800485 case MSG_RUN_CLEAR:
486 {
487 ClearParams params = (ClearParams)msg.obj;
488 (new PerformClearTask(params.transport, params.packageInfo)).run();
489 break;
490 }
491
492 case MSG_RUN_INITIALIZE:
493 {
494 HashSet<String> queue;
495
496 // Snapshot the pending-init queue and work on that
497 synchronized (mQueueLock) {
498 queue = new HashSet<String>(mPendingInits);
499 mPendingInits.clear();
500 }
501
502 (new PerformInitializeTask(queue)).run();
503 break;
504 }
505
Christopher Tate2d449afe2010-03-29 19:14:24 -0700506 case MSG_RUN_GET_RESTORE_SETS:
507 {
508 // Like other async operations, this is entered with the wakelock held
509 RestoreSet[] sets = null;
510 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
511 try {
512 sets = params.transport.getAvailableRestoreSets();
513 // cache the result in the active session
514 synchronized (params.session) {
515 params.session.mRestoreSets = sets;
516 }
517 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
518 } catch (Exception e) {
519 Slog.e(TAG, "Error from transport getting set list");
520 } finally {
521 if (params.observer != null) {
522 try {
523 params.observer.restoreSetsAvailable(sets);
524 } catch (RemoteException re) {
525 Slog.e(TAG, "Unable to report listing to observer");
526 } catch (Exception e) {
527 Slog.e(TAG, "Restore observer threw", e);
528 }
529 }
530
Christopher Tate2a935092011-03-03 17:30:32 -0800531 // Done: reset the session timeout clock
532 removeMessages(MSG_RESTORE_TIMEOUT);
533 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
534
Christopher Tate2d449afe2010-03-29 19:14:24 -0700535 mWakelock.release();
536 }
537 break;
538 }
539
Christopher Tate44a27902010-01-27 17:15:49 -0800540 case MSG_TIMEOUT:
541 {
542 synchronized (mCurrentOpLock) {
543 final int token = msg.arg1;
544 int state = mCurrentOperations.get(token, OP_TIMEOUT);
545 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800546 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800547 mCurrentOperations.put(token, OP_TIMEOUT);
548 }
549 mCurrentOpLock.notifyAll();
550 }
551 break;
552 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800553
554 case MSG_RESTORE_TIMEOUT:
555 {
556 synchronized (BackupManagerService.this) {
557 if (mActiveRestoreSession != null) {
558 // Client app left the restore session dangling. We know that it
559 // can't be in the middle of an actual restore operation because
560 // those are executed serially on this same handler thread. Clean
561 // up now.
562 Slog.w(TAG, "Restore session timed out; aborting");
563 post(mActiveRestoreSession.new EndRestoreRunnable(
564 BackupManagerService.this, mActiveRestoreSession));
565 }
566 }
567 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700568
569 case MSG_FULL_CONFIRMATION_TIMEOUT:
570 {
571 synchronized (mFullConfirmations) {
572 FullParams params = mFullConfirmations.get(msg.arg1);
573 if (params != null) {
574 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
575
576 // Release the waiter; timeout == completion
577 signalFullBackupRestoreCompletion(params);
578
579 // Remove the token from the set
580 mFullConfirmations.delete(msg.arg1);
581
582 // Report a timeout to the observer, if any
583 if (params.observer != null) {
584 try {
585 params.observer.onTimeout();
586 } catch (RemoteException e) {
587 /* don't care if the app has gone away */
588 }
589 }
590 } else {
591 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
592 }
593 }
594 break;
595 }
Christopher Tate44a27902010-01-27 17:15:49 -0800596 }
597 }
598 }
599
600 // ----- Main service implementation -----
601
Christopher Tate487529a2009-04-29 14:03:25 -0700602 public BackupManagerService(Context context) {
603 mContext = context;
604 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700605 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700606 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700607
Christopher Tateb6787f22009-07-02 17:40:45 -0700608 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
609 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
610
Christopher Tate44a27902010-01-27 17:15:49 -0800611 mBackupManagerBinder = asInterface(asBinder());
612
613 // spin up the backup/restore handler thread
614 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
615 mHandlerThread.start();
616 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
617
Christopher Tate22b87872009-05-04 16:41:53 -0700618 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700619 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700620 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700621 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700622 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800623 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800624 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800625 // If Encrypted file systems is enabled or disabled, this call will return the
626 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600627 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800628 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700629 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700630
Christopher Tate2efd2db2011-07-19 16:32:49 -0700631 mPasswordHashFile = new File(mBaseStateDir, "pwhash");
632 if (mPasswordHashFile.exists()) {
633 FileInputStream fin = null;
634 DataInputStream in = null;
635 try {
636 fin = new FileInputStream(mPasswordHashFile);
637 in = new DataInputStream(new BufferedInputStream(fin));
638 // integer length of the salt array, followed by the salt,
639 // then the hex pw hash string
640 int saltLen = in.readInt();
641 byte[] salt = new byte[saltLen];
642 in.readFully(salt);
643 mPasswordHash = in.readUTF();
644 mPasswordSalt = salt;
645 } catch (IOException e) {
646 Slog.e(TAG, "Unable to read saved backup pw hash");
647 } finally {
648 try {
649 if (in != null) in.close();
650 if (fin != null) fin.close();
651 } catch (IOException e) {
652 Slog.w(TAG, "Unable to close streams");
653 }
654 }
655 }
656
Christopher Tate4cc86e12009-09-21 19:36:51 -0700657 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700658 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700659 IntentFilter filter = new IntentFilter();
660 filter.addAction(RUN_BACKUP_ACTION);
661 context.registerReceiver(mRunBackupReceiver, filter,
662 android.Manifest.permission.BACKUP, null);
663
664 mRunInitReceiver = new RunInitializeReceiver();
665 filter = new IntentFilter();
666 filter.addAction(RUN_INITIALIZE_ACTION);
667 context.registerReceiver(mRunInitReceiver, filter,
668 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700669
670 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700671 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
672 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
673
Christopher Tate4cc86e12009-09-21 19:36:51 -0700674 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
675 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
676 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
677
Christopher Tatecde87f42009-06-12 12:55:53 -0700678 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700679 mJournalDir = new File(mBaseStateDir, "pending");
680 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700681 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700682
Christopher Tate73e02522009-07-15 14:18:26 -0700683 // Set up the various sorts of package tracking we do
684 initPackageTracking();
685
Christopher Tateabce4e82009-06-18 18:35:32 -0700686 // Build our mapping of uid to backup client services. This implicitly
687 // schedules a backup pass on the Package Manager metadata the first
688 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700689 synchronized (mBackupParticipants) {
690 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700691 }
692
Dan Egnor87a02bc2009-06-17 02:30:10 -0700693 // Set up our transport options and initialize the default transport
694 // TODO: Have transports register themselves somehow?
695 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700696 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700697 ComponentName localName = new ComponentName(context, LocalTransport.class);
698 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700699
Christopher Tate91717492009-06-26 21:07:13 -0700700 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700701 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
702 Settings.Secure.BACKUP_TRANSPORT);
703 if ("".equals(mCurrentTransport)) {
704 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700705 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800706 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700707
708 // Attach to the Google backup transport. When this comes up, it will set
709 // itself as the current transport because we explicitly reset mCurrentTransport
710 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700711 ComponentName transportComponent = new ComponentName("com.google.android.backup",
712 "com.google.android.backup.BackupTransportService");
713 try {
714 // If there's something out there that is supposed to be the Google
715 // backup transport, make sure it's legitimately part of the OS build
716 // and not an app lying about its package name.
717 ApplicationInfo info = mPackageManager.getApplicationInfo(
718 transportComponent.getPackageName(), 0);
719 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
720 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
721 Intent intent = new Intent().setComponent(transportComponent);
722 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
723 } else {
724 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
725 }
726 } catch (PackageManager.NameNotFoundException nnf) {
727 // No such package? No binding.
728 if (DEBUG) Slog.v(TAG, "Google transport not present");
729 }
Christopher Tateaa088442009-06-16 18:25:46 -0700730
Christopher Tatecde87f42009-06-12 12:55:53 -0700731 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700732 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700733 parseLeftoverJournals();
734
Christopher Tateb6787f22009-07-02 17:40:45 -0700735 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700736 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700737
738 // Start the backup passes going
739 setBackupEnabled(areEnabled);
740 }
741
742 private class RunBackupReceiver extends BroadcastReceiver {
743 public void onReceive(Context context, Intent intent) {
744 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700745 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700746 if (mPendingInits.size() > 0) {
747 // If there are pending init operations, we process those
748 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800749 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700750 try {
751 mAlarmManager.cancel(mRunInitIntent);
752 mRunInitIntent.send();
753 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800754 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700755 // can't really do more than bail here
756 }
757 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800758 // Don't run backups now if we're disabled or not yet
759 // fully set up.
760 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800761 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700762
763 // Acquire the wakelock and pass it to the backup thread. it will
764 // be released once backup concludes.
765 mWakelock.acquire();
766
767 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
768 mBackupHandler.sendMessage(msg);
769 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800770 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700771 }
772 }
773 }
774 }
775 }
776 }
777
778 private class RunInitializeReceiver extends BroadcastReceiver {
779 public void onReceive(Context context, Intent intent) {
780 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
781 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800782 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700783
784 // Acquire the wakelock and pass it to the init thread. it will
785 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700786 mWakelock.acquire();
787
Christopher Tate4cc86e12009-09-21 19:36:51 -0700788 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700789 mBackupHandler.sendMessage(msg);
790 }
791 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700792 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700793 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700794
Christopher Tate73e02522009-07-15 14:18:26 -0700795 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800796 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700797
Christopher Tate84725812010-02-04 15:52:40 -0800798 // Remember our ancestral dataset
799 mTokenFile = new File(mBaseStateDir, "ancestral");
800 try {
801 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800802 int version = tf.readInt();
803 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
804 mAncestralToken = tf.readLong();
805 mCurrentToken = tf.readLong();
806
807 int numPackages = tf.readInt();
808 if (numPackages >= 0) {
809 mAncestralPackages = new HashSet<String>();
810 for (int i = 0; i < numPackages; i++) {
811 String pkgName = tf.readUTF();
812 mAncestralPackages.add(pkgName);
813 }
814 }
815 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800816 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800817 } catch (FileNotFoundException fnf) {
818 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800819 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800820 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800821 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800822 }
823
Christopher Tatee97e8072009-07-15 16:45:50 -0700824 // Keep a log of what apps we've ever backed up. Because we might have
825 // rebooted in the middle of an operation that was removing something from
826 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700827 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700828 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700829
Christopher Tatee97e8072009-07-15 16:45:50 -0700830 // If we were in the middle of removing something from the ever-backed-up
831 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700832 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700833 if (tempProcessedFile.exists()) {
834 tempProcessedFile.delete();
835 }
836
Dan Egnor852f8e42009-09-30 11:20:45 -0700837 // If there are previous contents, parse them out then start a new
838 // file to continue the recordkeeping.
839 if (mEverStored.exists()) {
840 RandomAccessFile temp = null;
841 RandomAccessFile in = null;
842
843 try {
844 temp = new RandomAccessFile(tempProcessedFile, "rws");
845 in = new RandomAccessFile(mEverStored, "r");
846
847 while (true) {
848 PackageInfo info;
849 String pkg = in.readUTF();
850 try {
851 info = mPackageManager.getPackageInfo(pkg, 0);
852 mEverStoredApps.add(pkg);
853 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800854 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700855 } catch (NameNotFoundException e) {
856 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800857 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700858 }
859 }
860 } catch (EOFException e) {
861 // Once we've rewritten the backup history log, atomically replace the
862 // old one with the new one then reopen the file for continuing use.
863 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800864 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700865 }
866 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800867 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700868 } finally {
869 try { if (temp != null) temp.close(); } catch (IOException e) {}
870 try { if (in != null) in.close(); } catch (IOException e) {}
871 }
872 }
873
Christopher Tate73e02522009-07-15 14:18:26 -0700874 // Register for broadcasts about package install, etc., so we can
875 // update the provider list.
876 IntentFilter filter = new IntentFilter();
877 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
878 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
879 filter.addDataScheme("package");
880 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800881 // Register for events related to sdcard installation.
882 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800883 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
884 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800885 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700886 }
887
Christopher Tatecde87f42009-06-12 12:55:53 -0700888 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700889 for (File f : mJournalDir.listFiles()) {
890 if (mJournal == null || f.compareTo(mJournal) != 0) {
891 // This isn't the current journal, so it must be a leftover. Read
892 // out the package names mentioned there and schedule them for
893 // backup.
894 RandomAccessFile in = null;
895 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400896 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700897 in = new RandomAccessFile(f, "r");
898 while (true) {
899 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400900 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700901 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700902 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700903 } catch (EOFException e) {
904 // no more data; we're done
905 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800906 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700907 } finally {
908 // close/delete the file
909 try { if (in != null) in.close(); } catch (IOException e) {}
910 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700911 }
912 }
913 }
914 }
915
Christopher Tate2efd2db2011-07-19 16:32:49 -0700916 private SecretKey buildPasswordKey(String pw, byte[] salt, int rounds) {
917 return buildCharArrayKey(pw.toCharArray(), salt, rounds);
918 }
919
920 private SecretKey buildCharArrayKey(char[] pwArray, byte[] salt, int rounds) {
921 try {
922 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
923 KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
924 return keyFactory.generateSecret(ks);
925 } catch (InvalidKeySpecException e) {
926 Slog.e(TAG, "Invalid key spec for PBKDF2!");
927 } catch (NoSuchAlgorithmException e) {
928 Slog.e(TAG, "PBKDF2 unavailable!");
929 }
930 return null;
931 }
932
933 private String buildPasswordHash(String pw, byte[] salt, int rounds) {
934 SecretKey key = buildPasswordKey(pw, salt, rounds);
935 if (key != null) {
936 return byteArrayToHex(key.getEncoded());
937 }
938 return null;
939 }
940
941 private String byteArrayToHex(byte[] data) {
942 StringBuilder buf = new StringBuilder(data.length * 2);
943 for (int i = 0; i < data.length; i++) {
944 buf.append(Byte.toHexString(data[i], true));
945 }
946 return buf.toString();
947 }
948
949 private byte[] hexToByteArray(String digits) {
950 final int bytes = digits.length() / 2;
951 if (2*bytes != digits.length()) {
952 throw new IllegalArgumentException("Hex string must have an even number of digits");
953 }
954
955 byte[] result = new byte[bytes];
956 for (int i = 0; i < digits.length(); i += 2) {
957 result[i/2] = (byte) Integer.parseInt(digits.substring(i, i+2), 16);
958 }
959 return result;
960 }
961
962 private byte[] makeKeyChecksum(byte[] pwBytes, byte[] salt, int rounds) {
963 char[] mkAsChar = new char[pwBytes.length];
964 for (int i = 0; i < pwBytes.length; i++) {
965 mkAsChar[i] = (char) pwBytes[i];
966 }
967
968 Key checksum = buildCharArrayKey(mkAsChar, salt, rounds);
969 return checksum.getEncoded();
970 }
971
972 // Used for generating random salts or passwords
973 private byte[] randomBytes(int bits) {
974 byte[] array = new byte[bits / 8];
975 mRng.nextBytes(array);
976 return array;
977 }
978
979 // Backup password management
980 boolean passwordMatchesSaved(String candidatePw, int rounds) {
981 if (mPasswordHash == null) {
982 // no current password case -- require that 'currentPw' be null or empty
983 if (candidatePw == null || "".equals(candidatePw)) {
984 return true;
985 } // else the non-empty candidate does not match the empty stored pw
986 } else {
987 // hash the stated current pw and compare to the stored one
988 if (candidatePw != null && candidatePw.length() > 0) {
989 String currentPwHash = buildPasswordHash(candidatePw, mPasswordSalt, rounds);
990 if (mPasswordHash.equalsIgnoreCase(currentPwHash)) {
991 // candidate hash matches the stored hash -- the password matches
992 return true;
993 }
994 } // else the stored pw is nonempty but the candidate is empty; no match
995 }
996 return false;
997 }
998
999 @Override
1000 public boolean setBackupPassword(String currentPw, String newPw) {
1001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1002 "setBackupPassword");
1003
1004 // If the supplied pw doesn't hash to the the saved one, fail
1005 if (!passwordMatchesSaved(currentPw, PBKDF2_HASH_ROUNDS)) {
1006 return false;
1007 }
1008
1009 // Clearing the password is okay
1010 if (newPw == null || newPw.isEmpty()) {
1011 if (mPasswordHashFile.exists()) {
1012 if (!mPasswordHashFile.delete()) {
1013 // Unable to delete the old pw file, so fail
1014 Slog.e(TAG, "Unable to clear backup password");
1015 return false;
1016 }
1017 }
1018 mPasswordHash = null;
1019 mPasswordSalt = null;
1020 return true;
1021 }
1022
1023 try {
1024 // Okay, build the hash of the new backup password
1025 byte[] salt = randomBytes(PBKDF2_SALT_SIZE);
1026 String newPwHash = buildPasswordHash(newPw, salt, PBKDF2_HASH_ROUNDS);
1027
1028 OutputStream pwf = null, buffer = null;
1029 DataOutputStream out = null;
1030 try {
1031 pwf = new FileOutputStream(mPasswordHashFile);
1032 buffer = new BufferedOutputStream(pwf);
1033 out = new DataOutputStream(buffer);
1034 // integer length of the salt array, followed by the salt,
1035 // then the hex pw hash string
1036 out.writeInt(salt.length);
1037 out.write(salt);
1038 out.writeUTF(newPwHash);
1039 out.flush();
1040 mPasswordHash = newPwHash;
1041 mPasswordSalt = salt;
1042 return true;
1043 } finally {
1044 if (out != null) out.close();
1045 if (buffer != null) buffer.close();
1046 if (pwf != null) pwf.close();
1047 }
1048 } catch (IOException e) {
1049 Slog.e(TAG, "Unable to set backup password");
1050 }
1051 return false;
1052 }
1053
1054 @Override
1055 public boolean hasBackupPassword() {
1056 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1057 "hasBackupPassword");
1058 return (mPasswordHash != null && mPasswordHash.length() > 0);
1059 }
1060
Christopher Tate4cc86e12009-09-21 19:36:51 -07001061 // Maintain persistent state around whether need to do an initialize operation.
1062 // Must be called with the queue lock held.
1063 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001064 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -07001065 + " on transport " + transportName);
1066 try {
1067 IBackupTransport transport = getTransport(transportName);
1068 String transportDirName = transport.transportDirName();
1069 File stateDir = new File(mBaseStateDir, transportDirName);
1070 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1071
1072 if (isPending) {
1073 // We need an init before we can proceed with sending backup data.
1074 // Record that with an entry in our set of pending inits, as well as
1075 // journaling it via creation of a sentinel file.
1076 mPendingInits.add(transportName);
1077 try {
1078 (new FileOutputStream(initPendingFile)).close();
1079 } catch (IOException ioe) {
1080 // Something is badly wrong with our permissions; just try to move on
1081 }
1082 } else {
1083 // No more initialization needed; wipe the journal and reset our state.
1084 initPendingFile.delete();
1085 mPendingInits.remove(transportName);
1086 }
1087 } catch (RemoteException e) {
1088 // can't happen; the transport is local
1089 }
1090 }
1091
Christopher Tated55e18a2009-09-21 10:12:59 -07001092 // Reset all of our bookkeeping, in response to having been told that
1093 // the backend data has been wiped [due to idle expiry, for example],
1094 // so we must re-upload all saved settings.
1095 void resetBackupState(File stateFileDir) {
1096 synchronized (mQueueLock) {
1097 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -07001098 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -07001099 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001100
Christopher Tate84725812010-02-04 15:52:40 -08001101 mCurrentToken = 0;
1102 writeRestoreTokens();
1103
Christopher Tated55e18a2009-09-21 10:12:59 -07001104 // Remove all the state files
1105 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001106 // ... but don't touch the needs-init sentinel
1107 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
1108 sf.delete();
1109 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001110 }
Christopher Tate45597642011-04-04 16:59:21 -07001111 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001112
Christopher Tate45597642011-04-04 16:59:21 -07001113 // Enqueue a new backup of every participant
1114 int N = mBackupParticipants.size();
1115 for (int i=0; i<N; i++) {
1116 int uid = mBackupParticipants.keyAt(i);
1117 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1118 for (ApplicationInfo app: participants) {
1119 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -07001120 }
1121 }
1122 }
1123
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001124 // Add a transport to our set of available backends. If 'transport' is null, this
1125 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -07001126 private void registerTransport(String name, IBackupTransport transport) {
1127 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001128 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001129 if (transport != null) {
1130 mTransports.put(name, transport);
1131 } else {
1132 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -08001133 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -08001134 mCurrentTransport = null;
1135 }
1136 // Nothing further to do in the unregistration case
1137 return;
1138 }
Christopher Tate91717492009-06-26 21:07:13 -07001139 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001140
1141 // If the init sentinel file exists, we need to be sure to perform the init
1142 // as soon as practical. We also create the state directory at registration
1143 // time to ensure it's present from the outset.
1144 try {
1145 String transportName = transport.transportDirName();
1146 File stateDir = new File(mBaseStateDir, transportName);
1147 stateDir.mkdirs();
1148
1149 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
1150 if (initSentinel.exists()) {
1151 synchronized (mQueueLock) {
1152 mPendingInits.add(transportName);
1153
1154 // TODO: pick a better starting time than now + 1 minute
1155 long delay = 1000 * 60; // one minute, in milliseconds
1156 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1157 System.currentTimeMillis() + delay, mRunInitIntent);
1158 }
1159 }
1160 } catch (RemoteException e) {
1161 // can't happen, the transport is local
1162 }
Christopher Tate91717492009-06-26 21:07:13 -07001163 }
1164
Christopher Tate3799bc22009-05-06 16:13:56 -07001165 // ----- Track installation/removal of packages -----
1166 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1167 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001168 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -07001169
Christopher Tate3799bc22009-05-06 16:13:56 -07001170 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001171 boolean replacing = false;
1172 boolean added = false;
1173 Bundle extras = intent.getExtras();
1174 String pkgList[] = null;
1175 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
1176 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1177 Uri uri = intent.getData();
1178 if (uri == null) {
1179 return;
1180 }
1181 String pkgName = uri.getSchemeSpecificPart();
1182 if (pkgName != null) {
1183 pkgList = new String[] { pkgName };
1184 }
1185 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
1186 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001187 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001188 added = true;
1189 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001190 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001191 added = false;
1192 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1193 }
1194 if (pkgList == null || pkgList.length == 0) {
1195 return;
1196 }
1197 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001198 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001199 for (String pkgName : pkgList) {
1200 if (replacing) {
1201 // The package was just upgraded
1202 updatePackageParticipantsLocked(pkgName);
1203 } else {
1204 // The package was just added
1205 addPackageParticipantsLocked(pkgName);
1206 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001207 }
1208 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001209 } else {
1210 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -07001211 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
1212 } else {
1213 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001214 for (String pkgName : pkgList) {
1215 removePackageParticipantsLocked(pkgName);
1216 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001217 }
1218 }
1219 }
1220 }
1221 };
1222
Dan Egnor87a02bc2009-06-17 02:30:10 -07001223 // ----- Track connection to GoogleBackupTransport service -----
1224 ServiceConnection mGoogleConnection = new ServiceConnection() {
1225 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001226 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001227 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001228 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001229 }
1230
1231 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001232 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001233 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001234 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001235 }
1236 };
1237
Christopher Tate181fafa2009-05-14 11:12:14 -07001238 // Add the backup agents in the given package to our set of known backup participants.
1239 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001240 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001241 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001242 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001243 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001244 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001245 }
1246
Christopher Tate181fafa2009-05-14 11:12:14 -07001247 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001248 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001249 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001250 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001251 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001252 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001253 + " uid=" + p.applicationInfo.uid
1254 + " killAfterRestore="
1255 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001256 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001257 }
1258 }
1259
Dan Egnorefe52642009-06-24 00:16:33 -07001260 for (PackageInfo pkg : targetPkgs) {
1261 if (packageName == null || pkg.packageName.equals(packageName)) {
1262 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001263 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001264 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001265 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001266 mBackupParticipants.put(uid, set);
1267 }
Dan Egnorefe52642009-06-24 00:16:33 -07001268 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001269
1270 // If we've never seen this app before, schedule a backup for it
1271 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001272 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001273 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001274 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001275 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001276 }
Christopher Tate487529a2009-04-29 14:03:25 -07001277 }
1278 }
1279
Christopher Tate6785dd82009-06-18 15:58:25 -07001280 // Remove the given package's entry from our known active set. If
1281 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001282 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001283 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001284 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001285 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001286 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001287 } else {
1288 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001289 List<PackageInfo> knownPackages = allAgentPackages();
1290 for (PackageInfo pkg : knownPackages) {
1291 allApps.add(pkg.packageName);
1292 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001293 }
1294 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001295 }
1296
Joe Onorato8ad02812009-05-13 01:41:44 -04001297 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001298 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001299 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001300 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001301 + ") removing " + allPackageNames.size() + " entries");
1302 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001303 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001304 }
1305 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001306 for (String pkg : allPackageNames) {
1307 if (packageName == null || pkg.equals(packageName)) {
1308 int uid = -1;
1309 try {
1310 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1311 uid = info.applicationInfo.uid;
1312 } catch (NameNotFoundException e) {
1313 // we don't know this package name, so just skip it for now
1314 continue;
1315 }
1316
Christopher Tate181fafa2009-05-14 11:12:14 -07001317 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001318 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001319 // Find the existing entry with the same package name, and remove it.
1320 // We can't just remove(app) because the instances are different.
1321 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001322 if (entry.packageName.equals(pkg)) {
1323 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001324 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001325 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001326 break;
1327 }
1328 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001329 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001330 mBackupParticipants.delete(uid);
1331 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001332 }
1333 }
1334 }
1335 }
1336
Christopher Tate181fafa2009-05-14 11:12:14 -07001337 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001338 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001339 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001340 int flags = PackageManager.GET_SIGNATURES;
1341 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1342 int N = packages.size();
1343 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001344 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001345 try {
1346 ApplicationInfo app = pkg.applicationInfo;
1347 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001348 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001349 packages.remove(a);
1350 }
1351 else {
1352 // we will need the shared library path, so look that up and store it here
1353 app = mPackageManager.getApplicationInfo(pkg.packageName,
1354 PackageManager.GET_SHARED_LIBRARY_FILES);
1355 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1356 }
1357 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001358 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001359 }
1360 }
Dan Egnorefe52642009-06-24 00:16:33 -07001361 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001362 }
Christopher Tateaa088442009-06-16 18:25:46 -07001363
Christopher Tate3799bc22009-05-06 16:13:56 -07001364 // Reset the given package's known backup participants. Unlike add/remove, the update
1365 // action cannot be passed a null package name.
1366 void updatePackageParticipantsLocked(String packageName) {
1367 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001368 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001369 return;
1370 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001371 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001372
1373 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001374 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001375 List<String> allAppNames = new ArrayList<String>();
1376 for (PackageInfo pkg : allApps) {
1377 allAppNames.add(pkg.packageName);
1378 }
1379 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001380 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001381 }
1382
Christopher Tate84725812010-02-04 15:52:40 -08001383 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001384 // backed up at least once
1385 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001386 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1387
1388 synchronized (mEverStoredApps) {
1389 if (!mEverStoredApps.add(packageName)) return;
1390
1391 RandomAccessFile out = null;
1392 try {
1393 out = new RandomAccessFile(mEverStored, "rws");
1394 out.seek(out.length());
1395 out.writeUTF(packageName);
1396 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001397 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001398 } finally {
1399 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001400 }
1401 }
1402 }
1403
Christopher Tatee97e8072009-07-15 16:45:50 -07001404 // Remove our awareness of having ever backed up the given package
1405 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001406 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001407
Dan Egnor852f8e42009-09-30 11:20:45 -07001408 synchronized (mEverStoredApps) {
1409 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1410 // we'll recognize on initialization time that the package no longer
1411 // exists and fix it up then.
1412 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1413 RandomAccessFile known = null;
1414 try {
1415 known = new RandomAccessFile(tempKnownFile, "rws");
1416 mEverStoredApps.remove(packageName);
1417 for (String s : mEverStoredApps) {
1418 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001419 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001420 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001421 known.close();
1422 known = null;
1423 if (!tempKnownFile.renameTo(mEverStored)) {
1424 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1425 }
1426 } catch (IOException e) {
1427 // Bad: we couldn't create the new copy. For safety's sake we
1428 // abandon the whole process and remove all what's-backed-up
1429 // state entirely, meaning we'll force a backup pass for every
1430 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001431 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001432 mEverStoredApps.clear();
1433 tempKnownFile.delete();
1434 mEverStored.delete();
1435 } finally {
1436 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001437 }
1438 }
1439 }
1440
Christopher Tateb49ceb32010-02-08 16:22:24 -08001441 // Persistently record the current and ancestral backup tokens as well
1442 // as the set of packages with data [supposedly] available in the
1443 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001444 void writeRestoreTokens() {
1445 try {
1446 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001447
1448 // First, the version number of this record, for futureproofing
1449 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1450
1451 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001452 af.writeLong(mAncestralToken);
1453 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001454
1455 // Now write the set of ancestral packages
1456 if (mAncestralPackages == null) {
1457 af.writeInt(-1);
1458 } else {
1459 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001460 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001461 for (String pkgName : mAncestralPackages) {
1462 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001463 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001464 }
1465 }
Christopher Tate84725812010-02-04 15:52:40 -08001466 af.close();
1467 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001468 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001469 }
1470 }
1471
Dan Egnor87a02bc2009-06-17 02:30:10 -07001472 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001473 private IBackupTransport getTransport(String transportName) {
1474 synchronized (mTransports) {
1475 IBackupTransport transport = mTransports.get(transportName);
1476 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001477 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001478 }
1479 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001480 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001481 }
1482
Christopher Tatedf01dea2009-06-09 20:45:02 -07001483 // fire off a backup agent, blocking until it attaches or times out
1484 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1485 IBackupAgent agent = null;
1486 synchronized(mAgentConnectLock) {
1487 mConnecting = true;
1488 mConnectedAgent = null;
1489 try {
1490 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001491 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001492
1493 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001494 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001495 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1496 while (mConnecting && mConnectedAgent == null
1497 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001498 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001499 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001500 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001501 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001502 return null;
1503 }
1504 }
1505
1506 // if we timed out with no connect, abort and move on
1507 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001508 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001509 return null;
1510 }
1511 agent = mConnectedAgent;
1512 }
1513 } catch (RemoteException e) {
1514 // can't happen
1515 }
1516 }
1517 return agent;
1518 }
1519
Christopher Tatec7b31e32009-06-10 15:49:30 -07001520 // clear an application's data, blocking until the operation completes or times out
1521 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001522 // Don't wipe packages marked allowClearUserData=false
1523 try {
1524 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1525 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001526 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001527 + packageName);
1528 return;
1529 }
1530 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001531 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001532 return;
1533 }
1534
Christopher Tatec7b31e32009-06-10 15:49:30 -07001535 ClearDataObserver observer = new ClearDataObserver();
1536
1537 synchronized(mClearDataLock) {
1538 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001539 try {
1540 mActivityManager.clearApplicationUserData(packageName, observer);
1541 } catch (RemoteException e) {
1542 // can't happen because the activity manager is in this process
1543 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001544
1545 // only wait 10 seconds for the clear data to happen
1546 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1547 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1548 try {
1549 mClearDataLock.wait(5000);
1550 } catch (InterruptedException e) {
1551 // won't happen, but still.
1552 mClearingData = false;
1553 }
1554 }
1555 }
1556 }
1557
1558 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001559 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001560 synchronized(mClearDataLock) {
1561 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001562 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001563 }
1564 }
1565 }
1566
Christopher Tate1bb69062010-02-19 17:02:12 -08001567 // Get the restore-set token for the best-available restore set for this package:
1568 // the active set if possible, else the ancestral one. Returns zero if none available.
1569 long getAvailableRestoreToken(String packageName) {
1570 long token = mAncestralToken;
1571 synchronized (mQueueLock) {
1572 if (mEverStoredApps.contains(packageName)) {
1573 token = mCurrentToken;
1574 }
1575 }
1576 return token;
1577 }
1578
Christopher Tate44a27902010-01-27 17:15:49 -08001579 // -----
1580 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1581 boolean waitUntilOperationComplete(int token) {
1582 int finalState = OP_PENDING;
1583 synchronized (mCurrentOpLock) {
1584 try {
1585 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1586 try {
1587 mCurrentOpLock.wait();
1588 } catch (InterruptedException e) {}
1589 }
1590 } catch (IndexOutOfBoundsException e) {
1591 // the operation has been mysteriously cleared from our
1592 // bookkeeping -- consider this a success and ignore it.
1593 }
1594 }
1595 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001596 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001597 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001598 return finalState == OP_ACKNOWLEDGED;
1599 }
1600
1601 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001602 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001603 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001604 synchronized (mCurrentOpLock) {
1605 mCurrentOperations.put(token, OP_PENDING);
1606 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1607 mBackupHandler.sendMessageDelayed(msg, interval);
1608 }
Christopher Tate44a27902010-01-27 17:15:49 -08001609 }
1610
Christopher Tate043dadc2009-06-02 16:11:00 -07001611 // ----- Back up a set of applications via a worker thread -----
1612
Christopher Tate44a27902010-01-27 17:15:49 -08001613 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001614 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001615 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001616 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001617 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001618 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001619
Christopher Tate44a27902010-01-27 17:15:49 -08001620 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001621 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001622 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001623 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001624 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001625
1626 try {
1627 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1628 } catch (RemoteException e) {
1629 // can't happen; the transport is local
1630 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001631 }
1632
Christopher Tate043dadc2009-06-02 16:11:00 -07001633 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001634 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001635 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001637
Christopher Tate79588342009-06-30 16:11:49 -07001638 // Backups run at background priority
1639 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1640
Christopher Tate043dadc2009-06-02 16:11:00 -07001641 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001642 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001643
Dan Egnor852f8e42009-09-30 11:20:45 -07001644 // If we haven't stored package manager metadata yet, we must init the transport.
1645 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1646 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001647 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001648 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001649 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001650 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001651 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001652 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001653 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001654 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001655 }
Dan Egnor01445162009-09-21 17:04:05 -07001656 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001657
1658 // The package manager doesn't have a proper <application> etc, but since
1659 // it's running here in the system process we can just set up its agent
1660 // directly and use a synthetic BackupRequest. We always run this pass
1661 // because it's cheap and this way we guarantee that we don't get out of
1662 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001663 if (status == BackupConstants.TRANSPORT_OK) {
1664 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1665 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001666 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001667 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1668 status = processOneBackup(pmRequest,
1669 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1670 }
Christopher Tate90967f42009-09-20 15:28:33 -07001671
Dan Egnor01445162009-09-21 17:04:05 -07001672 if (status == BackupConstants.TRANSPORT_OK) {
1673 // Now run all the backups in our queue
1674 status = doQueuedBackups(mTransport);
1675 }
1676
1677 if (status == BackupConstants.TRANSPORT_OK) {
1678 // Tell the transport to finish everything it has buffered
1679 status = mTransport.finishBackup();
1680 if (status == BackupConstants.TRANSPORT_OK) {
1681 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001682 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001683 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001684 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001685 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001686 }
1687 }
1688
Dan Egnor01445162009-09-21 17:04:05 -07001689 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001690 // The backend reports that our dataset has been wiped. We need to
1691 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001692 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001693 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001694 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001695 }
1696 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001697 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001698 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001699 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001700 // If everything actually went through and this is the first time we've
1701 // done a backup, we can now record what the current backup dataset token
1702 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001703 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001704 try {
1705 mCurrentToken = mTransport.getCurrentRestoreSet();
1706 } catch (RemoteException e) { /* cannot happen */ }
1707 writeRestoreTokens();
1708 }
1709
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001710 // If things went wrong, we need to re-stage the apps we had expected
1711 // to be backing up in this pass. This journals the package names in
1712 // the current active pending-backup file, not in the we are holding
1713 // here in mJournal.
1714 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001715 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001716 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001717 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001718 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001719
1720 // We also want to reset the backup schedule based on whatever
1721 // the transport suggests by way of retry/backoff time.
1722 try {
1723 startBackupAlarmsLocked(mTransport.requestBackupTime());
1724 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001725 }
1726
1727 // Either backup was successful, in which case we of course do not need
1728 // this pass's journal any more; or it failed, in which case we just
1729 // re-enqueued all of these packages in the current active journal.
1730 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001731 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001732 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001733 }
1734
Christopher Tatec2af5d32010-02-02 15:18:58 -08001735 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001736 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001737 backupNow();
1738 }
1739
Dan Egnorbb9001c2009-07-27 12:20:13 -07001740 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001741 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001742 }
1743
Dan Egnor01445162009-09-21 17:04:05 -07001744 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001745 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001746 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001747
Christopher Tatec28083a2010-12-14 16:16:44 -08001748 // Verify that the requested app exists; it might be something that
1749 // requested a backup but was then uninstalled. The request was
1750 // journalled and rather than tamper with the journal it's safer
1751 // to sanity-check here.
1752 try {
1753 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1754 } catch (NameNotFoundException e) {
1755 Slog.d(TAG, "Package does not exist; skipping");
1756 continue;
1757 }
1758
Christopher Tate043dadc2009-06-02 16:11:00 -07001759 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001760 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001761 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001762 agent = bindToAgentSynchronous(request.appInfo,
1763 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001764 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001765 int result = processOneBackup(request, agent, transport);
1766 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001767 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001768 } catch (SecurityException ex) {
1769 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001770 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001771 } finally {
1772 try { // unbind even on timeout, just in case
1773 mActivityManager.unbindBackupAgent(request.appInfo);
1774 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001775 }
1776 }
Dan Egnor01445162009-09-21 17:04:05 -07001777
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001778 mWakelock.setWorkSource(null);
1779
Dan Egnor01445162009-09-21 17:04:05 -07001780 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001781 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001782
Dan Egnor01445162009-09-21 17:04:05 -07001783 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1784 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001785 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001786 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001787
Dan Egnorbb9001c2009-07-27 12:20:13 -07001788 File savedStateName = new File(mStateDir, packageName);
1789 File backupDataName = new File(mDataDir, packageName + ".data");
1790 File newStateName = new File(mStateDir, packageName + ".new");
1791
1792 ParcelFileDescriptor savedState = null;
1793 ParcelFileDescriptor backupData = null;
1794 ParcelFileDescriptor newState = null;
1795
1796 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001797 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001798 try {
1799 // Look up the package info & signatures. This is first so that if it
1800 // throws an exception, there's no file setup yet that would need to
1801 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001802 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1803 // The metadata 'package' is synthetic
1804 packInfo = new PackageInfo();
1805 packInfo.packageName = packageName;
1806 } else {
1807 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001808 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001809 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001810
Christopher Tatec7b31e32009-06-10 15:49:30 -07001811 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001812 // the saved-state "file". This is by definition an incremental,
1813 // so we build a saved state file to pass.
1814 savedState = ParcelFileDescriptor.open(savedStateName,
1815 ParcelFileDescriptor.MODE_READ_ONLY |
1816 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001817
Dan Egnorbb9001c2009-07-27 12:20:13 -07001818 backupData = ParcelFileDescriptor.open(backupDataName,
1819 ParcelFileDescriptor.MODE_READ_WRITE |
1820 ParcelFileDescriptor.MODE_CREATE |
1821 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001822
Dan Egnorbb9001c2009-07-27 12:20:13 -07001823 newState = ParcelFileDescriptor.open(newStateName,
1824 ParcelFileDescriptor.MODE_READ_WRITE |
1825 ParcelFileDescriptor.MODE_CREATE |
1826 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001827
Christopher Tate44a27902010-01-27 17:15:49 -08001828 // Initiate the target's backup pass
1829 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001830 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001831 boolean success = waitUntilOperationComplete(token);
1832
1833 if (!success) {
1834 // timeout -- bail out into the failed-transaction logic
1835 throw new RuntimeException("Backup timeout");
1836 }
1837
Dan Egnorbb9001c2009-07-27 12:20:13 -07001838 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001839 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001840 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001841 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001842 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001843 backupDataName.delete();
1844 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001845 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001846 } finally {
1847 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1848 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1849 try { if (newState != null) newState.close(); } catch (IOException e) {}
1850 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001851 synchronized (mCurrentOpLock) {
1852 mCurrentOperations.clear();
1853 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001854 }
1855
1856 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001857 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001858 try {
1859 int size = (int) backupDataName.length();
1860 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001861 if (result == BackupConstants.TRANSPORT_OK) {
1862 backupData = ParcelFileDescriptor.open(backupDataName,
1863 ParcelFileDescriptor.MODE_READ_ONLY);
1864 result = transport.performBackup(packInfo, backupData);
1865 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001866
Dan Egnor83861e72009-09-17 16:17:55 -07001867 // TODO - We call finishBackup() for each application backed up, because
1868 // we need to know now whether it succeeded or failed. Instead, we should
1869 // hold off on finishBackup() until the end, which implies holding off on
1870 // renaming *all* the output state files (see below) until that happens.
1871
Dan Egnor01445162009-09-21 17:04:05 -07001872 if (result == BackupConstants.TRANSPORT_OK) {
1873 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001874 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001875 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001876 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001877 }
1878
1879 // After successful transport, delete the now-stale data
1880 // and juggle the files so that next time we supply the agent
1881 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001882 if (result == BackupConstants.TRANSPORT_OK) {
1883 backupDataName.delete();
1884 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001885 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001886 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001887 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001888 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001889 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001890 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001891 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001892 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001893 } finally {
1894 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001895 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001896
Dan Egnor01445162009-09-21 17:04:05 -07001897 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001898 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001899 }
1900
Christopher Tatedf01dea2009-06-09 20:45:02 -07001901
Christopher Tate4a627c72011-04-01 14:43:32 -07001902 // ----- Full backup to a file/socket -----
1903
1904 class PerformFullBackupTask implements Runnable {
1905 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07001906 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07001907 IFullBackupRestoreObserver mObserver;
1908 boolean mIncludeApks;
1909 boolean mIncludeShared;
1910 boolean mAllApps;
1911 String[] mPackages;
Christopher Tate728a1c42011-07-28 18:03:03 -07001912 String mCurrentPassword;
1913 String mEncryptPassword;
Christopher Tate4a627c72011-04-01 14:43:32 -07001914 AtomicBoolean mLatchObject;
1915 File mFilesDir;
1916 File mManifestFile;
1917
Christopher Tate7926a692011-07-11 11:31:57 -07001918 class FullBackupRunner implements Runnable {
1919 PackageInfo mPackage;
1920 IBackupAgent mAgent;
1921 ParcelFileDescriptor mPipe;
1922 int mToken;
1923 boolean mSendApk;
1924
1925 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
1926 int token, boolean sendApk) throws IOException {
1927 mPackage = pack;
1928 mAgent = agent;
1929 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
1930 mToken = token;
1931 mSendApk = sendApk;
1932 }
1933
1934 @Override
1935 public void run() {
1936 try {
1937 BackupDataOutput output = new BackupDataOutput(
1938 mPipe.getFileDescriptor());
1939
1940 if (DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
1941 writeAppManifest(mPackage, mManifestFile, mSendApk);
1942 FullBackup.backupToTar(mPackage.packageName, null, null,
1943 mFilesDir.getAbsolutePath(),
1944 mManifestFile.getAbsolutePath(),
1945 output);
1946
1947 if (mSendApk) {
1948 writeApkToBackup(mPackage, output);
1949 }
1950
1951 if (DEBUG) Slog.d(TAG, "Calling doFullBackup()");
1952 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL);
1953 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
1954 } catch (IOException e) {
1955 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
1956 } catch (RemoteException e) {
1957 Slog.e(TAG, "Remote agent vanished during full backup of "
1958 + mPackage.packageName);
1959 } finally {
1960 try {
1961 mPipe.close();
1962 } catch (IOException e) {}
1963 }
1964 }
1965 }
1966
Christopher Tate4a627c72011-04-01 14:43:32 -07001967 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
Christopher Tate728a1c42011-07-28 18:03:03 -07001968 boolean includeApks, boolean includeShared, String curPassword,
1969 String encryptPassword, boolean doAllApps, String[] packages,
1970 AtomicBoolean latch) {
Christopher Tate4a627c72011-04-01 14:43:32 -07001971 mOutputFile = fd;
1972 mObserver = observer;
1973 mIncludeApks = includeApks;
1974 mIncludeShared = includeShared;
1975 mAllApps = doAllApps;
1976 mPackages = packages;
Christopher Tate728a1c42011-07-28 18:03:03 -07001977 mCurrentPassword = curPassword;
1978 // when backing up, if there is a current backup password, we require that
1979 // the user use a nonempty encryption password as well. if one is supplied
1980 // in the UI we use that, but if the UI was left empty we fall back to the
1981 // current backup password (which was supplied by the user as well).
1982 if (encryptPassword == null || "".equals(encryptPassword)) {
1983 mEncryptPassword = curPassword;
1984 } else {
1985 mEncryptPassword = encryptPassword;
1986 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001987 mLatchObject = latch;
1988
1989 mFilesDir = new File("/data/system");
1990 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1991 }
1992
1993 @Override
1994 public void run() {
1995 final List<PackageInfo> packagesToBackup;
1996
Christopher Tateb0628bf2011-06-02 15:08:13 -07001997 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07001998 sendStartBackup();
1999
2000 // doAllApps supersedes the package set if any
2001 if (mAllApps) {
2002 packagesToBackup = mPackageManager.getInstalledPackages(
2003 PackageManager.GET_SIGNATURES);
2004 } else {
2005 packagesToBackup = new ArrayList<PackageInfo>();
2006 for (String pkgName : mPackages) {
2007 try {
2008 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
2009 PackageManager.GET_SIGNATURES));
2010 } catch (NameNotFoundException e) {
2011 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
2012 }
2013 }
2014 }
2015
Christopher Tatea858cb02011-06-03 12:27:51 -07002016 // Cull any packages that have indicated that backups are not permitted.
2017 for (int i = 0; i < packagesToBackup.size(); ) {
2018 PackageInfo info = packagesToBackup.get(i);
2019 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2020 packagesToBackup.remove(i);
2021 } else {
2022 i++;
2023 }
2024 }
2025
Christopher Tate7926a692011-07-11 11:31:57 -07002026 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate2efd2db2011-07-19 16:32:49 -07002027 OutputStream out = null;
Christopher Tate7926a692011-07-11 11:31:57 -07002028
Christopher Tate4a627c72011-04-01 14:43:32 -07002029 PackageInfo pkg = null;
2030 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002031 boolean encrypting = (mEncryptPassword != null && mEncryptPassword.length() > 0);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002032 boolean compressing = COMPRESS_FULL_BACKUPS;
2033 OutputStream finalOutput = ofstream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002034
2035 // Write the global file header. All strings are UTF-8 encoded; lines end
2036 // with a '\n' byte. Actual backup data begins immediately following the
2037 // final '\n'.
2038 //
2039 // line 1: "ANDROID BACKUP"
2040 // line 2: backup file format version, currently "1"
2041 // line 3: compressed? "0" if not compressed, "1" if compressed.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002042 // line 4: name of encryption algorithm [currently only "none" or "AES-256"]
2043 //
2044 // When line 4 is not "none", then additional header data follows:
2045 //
2046 // line 5: user password salt [hex]
2047 // line 6: master key checksum salt [hex]
2048 // line 7: number of PBKDF2 rounds to use (same for user & master) [decimal]
2049 // line 8: IV of the user key [hex]
2050 // line 9: master key blob [hex]
2051 // IV of the master key, master key itself, master key checksum hash
2052 //
2053 // The master key checksum is the master key plus its checksum salt, run through
2054 // 10k rounds of PBKDF2. This is used to verify that the user has supplied the
2055 // correct password for decrypting the archive: the master key decrypted from
2056 // the archive using the user-supplied password is also run through PBKDF2 in
2057 // this way, and if the result does not match the checksum as stored in the
2058 // archive, then we know that the user-supplied password does not match the
2059 // archive's.
2060 StringBuilder headerbuf = new StringBuilder(1024);
2061
Christopher Tate7bdb0962011-07-13 19:30:21 -07002062 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002063 headerbuf.append(BACKUP_FILE_VERSION); // integer, no trailing \n
2064 headerbuf.append(compressing ? "\n1\n" : "\n0\n");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002065
2066 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002067 // Set up the encryption stage if appropriate, and emit the correct header
2068 if (encrypting) {
2069 // Verify that the given password matches the currently-active
2070 // backup password, if any
2071 if (hasBackupPassword()) {
Christopher Tate728a1c42011-07-28 18:03:03 -07002072 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002073 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2074 return;
2075 }
2076 }
2077
2078 finalOutput = emitAesBackupHeader(headerbuf, finalOutput);
2079 } else {
2080 headerbuf.append("none\n");
2081 }
2082
Christopher Tate7bdb0962011-07-13 19:30:21 -07002083 byte[] header = headerbuf.toString().getBytes("UTF-8");
2084 ofstream.write(header);
Christopher Tate2efd2db2011-07-19 16:32:49 -07002085
2086 // Set up the compression stage feeding into the encryption stage (if any)
2087 if (compressing) {
2088 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
2089 finalOutput = new DeflaterOutputStream(finalOutput, deflater, true);
2090 }
2091
2092 out = finalOutput;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002093 } catch (Exception e) {
2094 // Should never happen!
2095 Slog.e(TAG, "Unable to emit archive header", e);
2096 return;
2097 }
2098
Christopher Tateb0628bf2011-06-02 15:08:13 -07002099 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07002100 int N = packagesToBackup.size();
2101 for (int i = 0; i < N; i++) {
2102 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07002103 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002104 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002105
Christopher Tateb0628bf2011-06-02 15:08:13 -07002106 // Finally, shared storage if requested
2107 if (mIncludeShared) {
2108 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07002109 }
2110 } catch (RemoteException e) {
2111 Slog.e(TAG, "App died during full backup");
2112 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002113 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07002114 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002115 if (out != null) out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07002116 mOutputFile.close();
2117 } catch (IOException e) {
2118 /* nothing we can do about this */
2119 }
2120 synchronized (mCurrentOpLock) {
2121 mCurrentOperations.clear();
2122 }
2123 synchronized (mLatchObject) {
2124 mLatchObject.set(true);
2125 mLatchObject.notifyAll();
2126 }
2127 sendEndBackup();
2128 mWakelock.release();
2129 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
2130 }
2131 }
2132
Christopher Tate2efd2db2011-07-19 16:32:49 -07002133 private OutputStream emitAesBackupHeader(StringBuilder headerbuf,
2134 OutputStream ofstream) throws Exception {
2135 // User key will be used to encrypt the master key.
2136 byte[] newUserSalt = randomBytes(PBKDF2_SALT_SIZE);
Christopher Tate728a1c42011-07-28 18:03:03 -07002137 SecretKey userKey = buildPasswordKey(mEncryptPassword, newUserSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002138 PBKDF2_HASH_ROUNDS);
2139
2140 // the master key is random for each backup
2141 byte[] masterPw = new byte[256 / 8];
2142 mRng.nextBytes(masterPw);
2143 byte[] checksumSalt = randomBytes(PBKDF2_SALT_SIZE);
2144
2145 // primary encryption of the datastream with the random key
2146 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
2147 SecretKeySpec masterKeySpec = new SecretKeySpec(masterPw, "AES");
2148 c.init(Cipher.ENCRYPT_MODE, masterKeySpec);
2149 OutputStream finalOutput = new CipherOutputStream(ofstream, c);
2150
2151 // line 4: name of encryption algorithm
2152 headerbuf.append(ENCRYPTION_ALGORITHM_NAME);
2153 headerbuf.append('\n');
2154 // line 5: user password salt [hex]
2155 headerbuf.append(byteArrayToHex(newUserSalt));
2156 headerbuf.append('\n');
2157 // line 6: master key checksum salt [hex]
2158 headerbuf.append(byteArrayToHex(checksumSalt));
2159 headerbuf.append('\n');
2160 // line 7: number of PBKDF2 rounds used [decimal]
2161 headerbuf.append(PBKDF2_HASH_ROUNDS);
2162 headerbuf.append('\n');
2163
2164 // line 8: IV of the user key [hex]
2165 Cipher mkC = Cipher.getInstance("AES/CBC/PKCS5Padding");
2166 mkC.init(Cipher.ENCRYPT_MODE, userKey);
2167
2168 byte[] IV = mkC.getIV();
2169 headerbuf.append(byteArrayToHex(IV));
2170 headerbuf.append('\n');
2171
2172 // line 9: master IV + key blob, encrypted by the user key [hex]. Blob format:
2173 // [byte] IV length = Niv
2174 // [array of Niv bytes] IV itself
2175 // [byte] master key length = Nmk
2176 // [array of Nmk bytes] master key itself
2177 // [byte] MK checksum hash length = Nck
2178 // [array of Nck bytes] master key checksum hash
2179 //
2180 // The checksum is the (master key + checksum salt), run through the
2181 // stated number of PBKDF2 rounds
2182 IV = c.getIV();
2183 byte[] mk = masterKeySpec.getEncoded();
2184 byte[] checksum = makeKeyChecksum(masterKeySpec.getEncoded(),
2185 checksumSalt, PBKDF2_HASH_ROUNDS);
2186
2187 ByteArrayOutputStream blob = new ByteArrayOutputStream(IV.length + mk.length
2188 + checksum.length + 3);
2189 DataOutputStream mkOut = new DataOutputStream(blob);
2190 mkOut.writeByte(IV.length);
2191 mkOut.write(IV);
2192 mkOut.writeByte(mk.length);
2193 mkOut.write(mk);
2194 mkOut.writeByte(checksum.length);
2195 mkOut.write(checksum);
2196 mkOut.flush();
2197 byte[] encryptedMk = mkC.doFinal(blob.toByteArray());
2198 headerbuf.append(byteArrayToHex(encryptedMk));
2199 headerbuf.append('\n');
2200
2201 return finalOutput;
2202 }
2203
2204 private void backupOnePackage(PackageInfo pkg, OutputStream out)
Christopher Tate7926a692011-07-11 11:31:57 -07002205 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002206 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
2207
2208 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2209 IApplicationThread.BACKUP_MODE_FULL);
2210 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07002211 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002212 try {
Christopher Tate7926a692011-07-11 11:31:57 -07002213 pipes = ParcelFileDescriptor.createPipe();
2214
Christopher Tateb0628bf2011-06-02 15:08:13 -07002215 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07002216 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07002217 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
2218 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
2219 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
2220
2221 sendOnBackupPackage(pkg.packageName);
2222
Christopher Tate7926a692011-07-11 11:31:57 -07002223 final int token = generateToken();
2224 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
2225 token, sendApk);
2226 pipes[1].close(); // the runner has dup'd it
2227 pipes[1] = null;
2228 Thread t = new Thread(runner);
2229 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07002230
Christopher Tate7926a692011-07-11 11:31:57 -07002231 // Now pull data from the app and stuff it into the compressor
2232 try {
2233 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
2234 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002235
Christopher Tate7926a692011-07-11 11:31:57 -07002236 byte[] buffer = new byte[16 * 1024];
2237 int chunkTotal;
2238 while ((chunkTotal = in.readInt()) > 0) {
2239 while (chunkTotal > 0) {
2240 int toRead = (chunkTotal > buffer.length)
2241 ? buffer.length : chunkTotal;
2242 int nRead = in.read(buffer, 0, toRead);
2243 out.write(buffer, 0, nRead);
2244 chunkTotal -= nRead;
2245 }
2246 }
2247 } catch (IOException e) {
2248 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002249 }
2250
Christopher Tateb0628bf2011-06-02 15:08:13 -07002251 if (!waitUntilOperationComplete(token)) {
2252 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
2253 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07002254 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002255 }
Christopher Tate7926a692011-07-11 11:31:57 -07002256
Christopher Tateb0628bf2011-06-02 15:08:13 -07002257 } catch (IOException e) {
2258 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07002259 } finally {
2260 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002261 // flush after every package
2262 out.flush();
Christopher Tate7926a692011-07-11 11:31:57 -07002263 if (pipes != null) {
2264 if (pipes[0] != null) pipes[0].close();
2265 if (pipes[1] != null) pipes[1].close();
2266 }
Christopher Tate7926a692011-07-11 11:31:57 -07002267 } catch (IOException e) {
2268 Slog.w(TAG, "Error bringing down backup stack");
2269 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07002270 }
2271 } else {
2272 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
2273 }
2274 tearDown(pkg);
2275 }
2276
Christopher Tate79ec80d2011-06-24 14:58:49 -07002277 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
2278 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
2279 final String appSourceDir = pkg.applicationInfo.sourceDir;
2280 final String apkDir = new File(appSourceDir).getParent();
2281 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
2282 apkDir, appSourceDir, output);
2283
2284 // Save associated .obb content if it exists and we did save the apk
2285 // check for .obb and save those too
2286 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
2287 if (obbDir != null) {
2288 if (DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
2289 File[] obbFiles = obbDir.listFiles();
2290 if (obbFiles != null) {
2291 final String obbDirName = obbDir.getAbsolutePath();
2292 for (File obb : obbFiles) {
2293 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
2294 obbDirName, obb.getAbsolutePath(), output);
2295 }
2296 }
2297 }
2298 }
2299
Christopher Tateb0628bf2011-06-02 15:08:13 -07002300 private void backupSharedStorage() throws RemoteException {
2301 PackageInfo pkg = null;
2302 try {
2303 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
2304 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
2305 IApplicationThread.BACKUP_MODE_FULL);
2306 if (agent != null) {
2307 sendOnBackupPackage("Shared storage");
2308
2309 final int token = generateToken();
2310 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07002311 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07002312 if (!waitUntilOperationComplete(token)) {
2313 Slog.e(TAG, "Full backup failed on shared storage");
2314 } else {
2315 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
2316 }
2317 } else {
2318 Slog.e(TAG, "Could not bind to shared storage backup agent");
2319 }
2320 } catch (NameNotFoundException e) {
2321 Slog.e(TAG, "Shared storage backup package not found");
2322 } finally {
2323 tearDown(pkg);
2324 }
2325 }
2326
Christopher Tate4a627c72011-04-01 14:43:32 -07002327 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
2328 throws IOException {
2329 // Manifest format. All data are strings ending in LF:
2330 // BACKUP_MANIFEST_VERSION, currently 1
2331 //
2332 // Version 1:
2333 // package name
2334 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002335 // platform versionCode
2336 // getInstallerPackageName() for this package (maybe empty)
2337 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002338 // number of signatures == N
2339 // N*: signature byte array in ascii format per Signature.toCharsString()
2340 StringBuilder builder = new StringBuilder(4096);
2341 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2342
2343 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2344 printer.println(pkg.packageName);
2345 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002346 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2347
2348 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2349 printer.println((installerName != null) ? installerName : "");
2350
Christopher Tate4a627c72011-04-01 14:43:32 -07002351 printer.println(withApk ? "1" : "0");
2352 if (pkg.signatures == null) {
2353 printer.println("0");
2354 } else {
2355 printer.println(Integer.toString(pkg.signatures.length));
2356 for (Signature sig : pkg.signatures) {
2357 printer.println(sig.toCharsString());
2358 }
2359 }
2360
2361 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002362 outstream.write(builder.toString().getBytes());
2363 outstream.close();
2364 }
2365
2366 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002367 if (pkg != null) {
2368 final ApplicationInfo app = pkg.applicationInfo;
2369 if (app != null) {
2370 try {
2371 // unbind and tidy up even on timeout or failure, just in case
2372 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002373
Christopher Tateb0628bf2011-06-02 15:08:13 -07002374 // The agent was running with a stub Application object, so shut it down.
Christopher Tate2efd2db2011-07-19 16:32:49 -07002375 if (app.uid != Process.SYSTEM_UID
2376 && app.uid != Process.PHONE_UID) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002377 if (DEBUG) Slog.d(TAG, "Backup complete, killing host process");
2378 mActivityManager.killApplicationProcess(app.processName, app.uid);
2379 } else {
2380 if (DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
2381 }
2382 } catch (RemoteException e) {
2383 Slog.d(TAG, "Lost app trying to shut down");
2384 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002385 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002386 }
2387 }
2388
2389 // wrappers for observer use
2390 void sendStartBackup() {
2391 if (mObserver != null) {
2392 try {
2393 mObserver.onStartBackup();
2394 } catch (RemoteException e) {
2395 Slog.w(TAG, "full backup observer went away: startBackup");
2396 mObserver = null;
2397 }
2398 }
2399 }
2400
2401 void sendOnBackupPackage(String name) {
2402 if (mObserver != null) {
2403 try {
2404 // TODO: use a more user-friendly name string
2405 mObserver.onBackupPackage(name);
2406 } catch (RemoteException e) {
2407 Slog.w(TAG, "full backup observer went away: backupPackage");
2408 mObserver = null;
2409 }
2410 }
2411 }
2412
2413 void sendEndBackup() {
2414 if (mObserver != null) {
2415 try {
2416 mObserver.onEndBackup();
2417 } catch (RemoteException e) {
2418 Slog.w(TAG, "full backup observer went away: endBackup");
2419 mObserver = null;
2420 }
2421 }
2422 }
2423 }
2424
2425
Christopher Tate75a99702011-05-18 16:28:19 -07002426 // ----- Full restore from a file/socket -----
2427
2428 // Description of a file in the restore datastream
2429 static class FileMetadata {
2430 String packageName; // name of the owning app
2431 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002432 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002433 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2434 String path; // subpath within the semantic domain
2435 long mode; // e.g. 0666 (actually int)
2436 long mtime; // last mod time, UTC time_t (actually int)
2437 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002438
2439 @Override
2440 public String toString() {
2441 StringBuilder sb = new StringBuilder(128);
2442 sb.append("FileMetadata{");
2443 sb.append(packageName); sb.append(',');
2444 sb.append(type); sb.append(',');
2445 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2446 sb.append(size);
2447 sb.append('}');
2448 return sb.toString();
2449 }
Christopher Tate75a99702011-05-18 16:28:19 -07002450 }
2451
2452 enum RestorePolicy {
2453 IGNORE,
2454 ACCEPT,
2455 ACCEPT_IF_APK
2456 }
2457
2458 class PerformFullRestoreTask implements Runnable {
2459 ParcelFileDescriptor mInputFile;
Christopher Tate728a1c42011-07-28 18:03:03 -07002460 String mCurrentPassword;
2461 String mDecryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002462 IFullBackupRestoreObserver mObserver;
2463 AtomicBoolean mLatchObject;
2464 IBackupAgent mAgent;
2465 String mAgentPackage;
2466 ApplicationInfo mTargetApp;
2467 ParcelFileDescriptor[] mPipes = null;
2468
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002469 long mBytes;
2470
Christopher Tate75a99702011-05-18 16:28:19 -07002471 // possible handling states for a given package in the restore dataset
2472 final HashMap<String, RestorePolicy> mPackagePolicies
2473 = new HashMap<String, RestorePolicy>();
2474
2475 // installer package names for each encountered app, derived from the manifests
2476 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2477
2478 // Signatures for a given package found in its manifest file
2479 final HashMap<String, Signature[]> mManifestSignatures
2480 = new HashMap<String, Signature[]>();
2481
2482 // Packages we've already wiped data on when restoring their first file
2483 final HashSet<String> mClearedPackages = new HashSet<String>();
2484
Christopher Tate728a1c42011-07-28 18:03:03 -07002485 PerformFullRestoreTask(ParcelFileDescriptor fd, String curPassword, String decryptPassword,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002486 IFullBackupRestoreObserver observer, AtomicBoolean latch) {
Christopher Tate75a99702011-05-18 16:28:19 -07002487 mInputFile = fd;
Christopher Tate728a1c42011-07-28 18:03:03 -07002488 mCurrentPassword = curPassword;
2489 mDecryptPassword = decryptPassword;
Christopher Tate75a99702011-05-18 16:28:19 -07002490 mObserver = observer;
2491 mLatchObject = latch;
2492 mAgent = null;
2493 mAgentPackage = null;
2494 mTargetApp = null;
2495
2496 // Which packages we've already wiped data on. We prepopulate this
2497 // with a whitelist of packages known to be unclearable.
2498 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002499 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002500
Christopher Tate75a99702011-05-18 16:28:19 -07002501 }
2502
2503 class RestoreFileRunnable implements Runnable {
2504 IBackupAgent mAgent;
2505 FileMetadata mInfo;
2506 ParcelFileDescriptor mSocket;
2507 int mToken;
2508
2509 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2510 ParcelFileDescriptor socket, int token) throws IOException {
2511 mAgent = agent;
2512 mInfo = info;
2513 mToken = token;
2514
2515 // This class is used strictly for process-local binder invocations. The
2516 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2517 // do not automatically get a 'dup'ed descriptor that we can can continue
2518 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2519 // before proceeding to do the restore.
2520 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2521 }
2522
2523 @Override
2524 public void run() {
2525 try {
2526 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2527 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2528 mToken, mBackupManagerBinder);
2529 } catch (RemoteException e) {
2530 // never happens; this is used strictly for local binder calls
2531 }
2532 }
2533 }
2534
2535 @Override
2536 public void run() {
2537 Slog.i(TAG, "--- Performing full-dataset restore ---");
2538 sendStartRestore();
2539
Christopher Tateb0628bf2011-06-02 15:08:13 -07002540 // Are we able to restore shared-storage data?
2541 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2542 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2543 }
2544
Christopher Tate2efd2db2011-07-19 16:32:49 -07002545 FileInputStream rawInStream = null;
2546 DataInputStream rawDataIn = null;
Christopher Tate75a99702011-05-18 16:28:19 -07002547 try {
Christopher Tate728a1c42011-07-28 18:03:03 -07002548 if (hasBackupPassword()) {
2549 if (!passwordMatchesSaved(mCurrentPassword, PBKDF2_HASH_ROUNDS)) {
2550 if (DEBUG) Slog.w(TAG, "Backup password mismatch; aborting");
2551 return;
2552 }
2553 }
2554
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002555 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002556 byte[] buffer = new byte[32 * 1024];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002557 rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
2558 rawDataIn = new DataInputStream(rawInStream);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002559
2560 // First, parse out the unencrypted/uncompressed header
2561 boolean compressed = false;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002562 InputStream preCompressStream = rawInStream;
Christopher Tate7bdb0962011-07-13 19:30:21 -07002563 final InputStream in;
2564
2565 boolean okay = false;
2566 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2567 byte[] streamHeader = new byte[headerLen];
Christopher Tate2efd2db2011-07-19 16:32:49 -07002568 rawDataIn.readFully(streamHeader);
2569 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2570 if (Arrays.equals(magicBytes, streamHeader)) {
2571 // okay, header looks good. now parse out the rest of the fields.
2572 String s = readHeaderLine(rawInStream);
2573 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2574 // okay, it's a version we recognize
2575 s = readHeaderLine(rawInStream);
2576 compressed = (Integer.parseInt(s) != 0);
2577 s = readHeaderLine(rawInStream);
2578 if (s.equals("none")) {
2579 // no more header to parse; we're good to go
2580 okay = true;
Christopher Tate728a1c42011-07-28 18:03:03 -07002581 } else if (mDecryptPassword != null && mDecryptPassword.length() > 0) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002582 preCompressStream = decodeAesHeaderAndInitialize(s, rawInStream);
2583 if (preCompressStream != null) {
Christopher Tate7bdb0962011-07-13 19:30:21 -07002584 okay = true;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002585 }
2586 } else Slog.w(TAG, "Archive is encrypted but no password given");
2587 } else Slog.w(TAG, "Wrong header version: " + s);
2588 } else Slog.w(TAG, "Didn't read the right header magic");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002589
2590 if (!okay) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002591 Slog.w(TAG, "Invalid restore data; aborting.");
Christopher Tate7bdb0962011-07-13 19:30:21 -07002592 return;
2593 }
2594
2595 // okay, use the right stream layer based on compression
Christopher Tate2efd2db2011-07-19 16:32:49 -07002596 in = (compressed) ? new InflaterInputStream(preCompressStream) : preCompressStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002597
2598 boolean didRestore;
2599 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002600 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002601 } while (didRestore);
2602
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002603 if (DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002604 } catch (IOException e) {
2605 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002606 } finally {
2607 tearDownPipes();
2608 tearDownAgent(mTargetApp);
2609
2610 try {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002611 if (rawDataIn != null) rawDataIn.close();
2612 if (rawInStream != null) rawInStream.close();
Christopher Tate75a99702011-05-18 16:28:19 -07002613 mInputFile.close();
2614 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002615 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002616 /* nothing we can do about this */
2617 }
2618 synchronized (mCurrentOpLock) {
2619 mCurrentOperations.clear();
2620 }
2621 synchronized (mLatchObject) {
2622 mLatchObject.set(true);
2623 mLatchObject.notifyAll();
2624 }
2625 sendEndRestore();
2626 mWakelock.release();
2627 if (DEBUG) Slog.d(TAG, "Full restore pass complete.");
2628 }
2629 }
2630
Christopher Tate7bdb0962011-07-13 19:30:21 -07002631 String readHeaderLine(InputStream in) throws IOException {
2632 int c;
Christopher Tate2efd2db2011-07-19 16:32:49 -07002633 StringBuilder buffer = new StringBuilder(80);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002634 while ((c = in.read()) >= 0) {
2635 if (c == '\n') break; // consume and discard the newlines
2636 buffer.append((char)c);
2637 }
2638 return buffer.toString();
2639 }
2640
Christopher Tate2efd2db2011-07-19 16:32:49 -07002641 InputStream decodeAesHeaderAndInitialize(String encryptionName, InputStream rawInStream) {
2642 InputStream result = null;
2643 try {
2644 if (encryptionName.equals(ENCRYPTION_ALGORITHM_NAME)) {
2645
2646 String userSaltHex = readHeaderLine(rawInStream); // 5
2647 byte[] userSalt = hexToByteArray(userSaltHex);
2648
2649 String ckSaltHex = readHeaderLine(rawInStream); // 6
2650 byte[] ckSalt = hexToByteArray(ckSaltHex);
2651
2652 int rounds = Integer.parseInt(readHeaderLine(rawInStream)); // 7
2653 String userIvHex = readHeaderLine(rawInStream); // 8
2654
2655 String masterKeyBlobHex = readHeaderLine(rawInStream); // 9
2656
2657 // decrypt the master key blob
2658 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Christopher Tate728a1c42011-07-28 18:03:03 -07002659 SecretKey userKey = buildPasswordKey(mDecryptPassword, userSalt,
Christopher Tate2efd2db2011-07-19 16:32:49 -07002660 rounds);
2661 byte[] IV = hexToByteArray(userIvHex);
2662 IvParameterSpec ivSpec = new IvParameterSpec(IV);
2663 c.init(Cipher.DECRYPT_MODE,
2664 new SecretKeySpec(userKey.getEncoded(), "AES"),
2665 ivSpec);
2666 byte[] mkCipher = hexToByteArray(masterKeyBlobHex);
2667 byte[] mkBlob = c.doFinal(mkCipher);
2668
2669 // first, the master key IV
2670 int offset = 0;
2671 int len = mkBlob[offset++];
2672 IV = Arrays.copyOfRange(mkBlob, offset, offset + len);
2673 offset += len;
2674 // then the master key itself
2675 len = mkBlob[offset++];
2676 byte[] mk = Arrays.copyOfRange(mkBlob,
2677 offset, offset + len);
2678 offset += len;
2679 // and finally the master key checksum hash
2680 len = mkBlob[offset++];
2681 byte[] mkChecksum = Arrays.copyOfRange(mkBlob,
2682 offset, offset + len);
2683
2684 // now validate the decrypted master key against the checksum
2685 byte[] calculatedCk = makeKeyChecksum(mk, ckSalt, rounds);
2686 if (Arrays.equals(calculatedCk, mkChecksum)) {
2687 ivSpec = new IvParameterSpec(IV);
2688 c.init(Cipher.DECRYPT_MODE,
2689 new SecretKeySpec(mk, "AES"),
2690 ivSpec);
2691 // Only if all of the above worked properly will 'result' be assigned
2692 result = new CipherInputStream(rawInStream, c);
2693 } else Slog.w(TAG, "Incorrect password");
2694 } else Slog.w(TAG, "Unsupported encryption method: " + encryptionName);
2695 } catch (InvalidAlgorithmParameterException e) {
2696 Slog.e(TAG, "Needed parameter spec unavailable!", e);
2697 } catch (BadPaddingException e) {
2698 // This case frequently occurs when the wrong password is used to decrypt
2699 // the master key. Use the identical "incorrect password" log text as is
2700 // used in the checksum failure log in order to avoid providing additional
2701 // information to an attacker.
2702 Slog.w(TAG, "Incorrect password");
2703 } catch (IllegalBlockSizeException e) {
2704 Slog.w(TAG, "Invalid block size in master key");
2705 } catch (NoSuchAlgorithmException e) {
2706 Slog.e(TAG, "Needed decryption algorithm unavailable!");
2707 } catch (NoSuchPaddingException e) {
2708 Slog.e(TAG, "Needed padding mechanism unavailable!");
2709 } catch (InvalidKeyException e) {
2710 Slog.w(TAG, "Illegal password; aborting");
2711 } catch (NumberFormatException e) {
2712 Slog.w(TAG, "Can't parse restore data header");
2713 } catch (IOException e) {
2714 Slog.w(TAG, "Can't read input header");
2715 }
2716
2717 return result;
2718 }
2719
Christopher Tate75a99702011-05-18 16:28:19 -07002720 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2721 FileMetadata info;
2722 try {
2723 info = readTarHeaders(instream);
2724 if (info != null) {
2725 if (DEBUG) {
2726 dumpFileMetadata(info);
2727 }
2728
2729 final String pkg = info.packageName;
2730 if (!pkg.equals(mAgentPackage)) {
2731 // okay, change in package; set up our various
2732 // bookkeeping if we haven't seen it yet
2733 if (!mPackagePolicies.containsKey(pkg)) {
2734 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2735 }
2736
2737 // Clean up the previous agent relationship if necessary,
2738 // and let the observer know we're considering a new app.
2739 if (mAgent != null) {
2740 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2741 tearDownPipes();
2742 tearDownAgent(mTargetApp);
2743 mTargetApp = null;
2744 mAgentPackage = null;
2745 }
2746 }
2747
2748 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2749 mPackagePolicies.put(pkg, readAppManifest(info, instream));
2750 mPackageInstallers.put(pkg, info.installerPackageName);
2751 // We've read only the manifest content itself at this point,
2752 // so consume the footer before looping around to the next
2753 // input file
2754 skipTarPadding(info.size, instream);
2755 sendOnRestorePackage(pkg);
2756 } else {
2757 // Non-manifest, so it's actual file data. Is this a package
2758 // we're ignoring?
2759 boolean okay = true;
2760 RestorePolicy policy = mPackagePolicies.get(pkg);
2761 switch (policy) {
2762 case IGNORE:
2763 okay = false;
2764 break;
2765
2766 case ACCEPT_IF_APK:
2767 // If we're in accept-if-apk state, then the first file we
2768 // see MUST be the apk.
2769 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2770 if (DEBUG) Slog.d(TAG, "APK file; installing");
2771 // Try to install the app.
2772 String installerName = mPackageInstallers.get(pkg);
2773 okay = installApk(info, installerName, instream);
2774 // good to go; promote to ACCEPT
2775 mPackagePolicies.put(pkg, (okay)
2776 ? RestorePolicy.ACCEPT
2777 : RestorePolicy.IGNORE);
2778 // At this point we've consumed this file entry
2779 // ourselves, so just strip the tar footer and
2780 // go on to the next file in the input stream
2781 skipTarPadding(info.size, instream);
2782 return true;
2783 } else {
2784 // File data before (or without) the apk. We can't
2785 // handle it coherently in this case so ignore it.
2786 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2787 okay = false;
2788 }
2789 break;
2790
2791 case ACCEPT:
2792 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2793 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
2794 // we can take the data without the apk, so we
2795 // *want* to do so. skip the apk by declaring this
2796 // one file not-okay without changing the restore
2797 // policy for the package.
2798 okay = false;
2799 }
2800 break;
2801
2802 default:
2803 // Something has gone dreadfully wrong when determining
2804 // the restore policy from the manifest. Ignore the
2805 // rest of this package's data.
2806 Slog.e(TAG, "Invalid policy from manifest");
2807 okay = false;
2808 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2809 break;
2810 }
2811
2812 // If the policy is satisfied, go ahead and set up to pipe the
2813 // data to the agent.
2814 if (DEBUG && okay && mAgent != null) {
2815 Slog.i(TAG, "Reusing existing agent instance");
2816 }
2817 if (okay && mAgent == null) {
2818 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
2819
2820 try {
2821 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
2822
2823 // If we haven't sent any data to this app yet, we probably
2824 // need to clear it first. Check that.
2825 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002826 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07002827 // responsible for coherently managing a full
2828 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07002829 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07002830 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
2831 clearApplicationDataSynchronous(pkg);
2832 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002833 if (DEBUG) Slog.d(TAG, "backup agent ("
2834 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07002835 }
2836 mClearedPackages.add(pkg);
2837 } else {
2838 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
2839 }
2840
2841 // All set; now set up the IPC and launch the agent
2842 setUpPipes();
2843 mAgent = bindToAgentSynchronous(mTargetApp,
2844 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
2845 mAgentPackage = pkg;
2846 } catch (IOException e) {
2847 // fall through to error handling
2848 } catch (NameNotFoundException e) {
2849 // fall through to error handling
2850 }
2851
2852 if (mAgent == null) {
2853 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
2854 okay = false;
2855 tearDownPipes();
2856 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2857 }
2858 }
2859
2860 // Sanity check: make sure we never give data to the wrong app. This
2861 // should never happen but a little paranoia here won't go amiss.
2862 if (okay && !pkg.equals(mAgentPackage)) {
2863 Slog.e(TAG, "Restoring data for " + pkg
2864 + " but agent is for " + mAgentPackage);
2865 okay = false;
2866 }
2867
2868 // At this point we have an agent ready to handle the full
2869 // restore data as well as a pipe for sending data to
2870 // that agent. Tell the agent to start reading from the
2871 // pipe.
2872 if (okay) {
2873 boolean agentSuccess = true;
2874 long toCopy = info.size;
2875 final int token = generateToken();
2876 try {
2877 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
2878 + info.path);
2879 prepareOperationTimeout(token,
2880 TIMEOUT_FULL_BACKUP_INTERVAL);
2881 // fire up the app's agent listening on the socket. If
2882 // the agent is running in the system process we can't
2883 // just invoke it asynchronously, so we provide a thread
2884 // for it here.
2885 if (mTargetApp.processName.equals("system")) {
2886 Slog.d(TAG, "system process agent - spinning a thread");
2887 RestoreFileRunnable runner = new RestoreFileRunnable(
2888 mAgent, info, mPipes[0], token);
2889 new Thread(runner).start();
2890 } else {
2891 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
2892 info.domain, info.path, info.mode, info.mtime,
2893 token, mBackupManagerBinder);
2894 }
2895 } catch (IOException e) {
2896 // couldn't dup the socket for a process-local restore
2897 Slog.d(TAG, "Couldn't establish restore");
2898 agentSuccess = false;
2899 okay = false;
2900 } catch (RemoteException e) {
2901 // whoops, remote agent went away. We'll eat the content
2902 // ourselves, then, and not copy it over.
2903 Slog.e(TAG, "Agent crashed during full restore");
2904 agentSuccess = false;
2905 okay = false;
2906 }
2907
2908 // Copy over the data if the agent is still good
2909 if (okay) {
2910 boolean pipeOkay = true;
2911 FileOutputStream pipe = new FileOutputStream(
2912 mPipes[1].getFileDescriptor());
2913 if (DEBUG) Slog.d(TAG, "Piping data to agent");
2914 while (toCopy > 0) {
2915 int toRead = (toCopy > buffer.length)
2916 ? buffer.length : (int)toCopy;
2917 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002918 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002919 if (nRead <= 0) break;
2920 toCopy -= nRead;
2921
2922 // send it to the output pipe as long as things
2923 // are still good
2924 if (pipeOkay) {
2925 try {
2926 pipe.write(buffer, 0, nRead);
2927 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002928 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002929 pipeOkay = false;
2930 }
2931 }
2932 }
2933
2934 // done sending that file! Now we just need to consume
2935 // the delta from info.size to the end of block.
2936 skipTarPadding(info.size, instream);
2937
2938 // and now that we've sent it all, wait for the remote
2939 // side to acknowledge receipt
2940 agentSuccess = waitUntilOperationComplete(token);
2941 }
2942
2943 // okay, if the remote end failed at any point, deal with
2944 // it by ignoring the rest of the restore on it
2945 if (!agentSuccess) {
2946 mBackupHandler.removeMessages(MSG_TIMEOUT);
2947 tearDownPipes();
2948 tearDownAgent(mTargetApp);
2949 mAgent = null;
2950 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2951 }
2952 }
2953
2954 // Problems setting up the agent communication, or an already-
2955 // ignored package: skip to the next tar stream entry by
2956 // reading and discarding this file.
2957 if (!okay) {
2958 if (DEBUG) Slog.d(TAG, "[discarding file content]");
2959 long bytesToConsume = (info.size + 511) & ~511;
2960 while (bytesToConsume > 0) {
2961 int toRead = (bytesToConsume > buffer.length)
2962 ? buffer.length : (int)bytesToConsume;
2963 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002964 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002965 if (nRead <= 0) break;
2966 bytesToConsume -= nRead;
2967 }
2968 }
2969 }
2970 }
2971 } catch (IOException e) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07002972 if (DEBUG) Slog.w(TAG, "io exception on restore socket read", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002973 // treat as EOF
2974 info = null;
2975 }
2976
2977 return (info != null);
2978 }
2979
2980 void setUpPipes() throws IOException {
2981 mPipes = ParcelFileDescriptor.createPipe();
2982 }
2983
2984 void tearDownPipes() {
2985 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002986 try {
2987 mPipes[0].close();
2988 mPipes[0] = null;
2989 mPipes[1].close();
2990 mPipes[1] = null;
2991 } catch (IOException e) {
2992 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002993 }
2994 mPipes = null;
2995 }
2996 }
2997
2998 void tearDownAgent(ApplicationInfo app) {
2999 if (mAgent != null) {
3000 try {
3001 // unbind and tidy up even on timeout or failure, just in case
3002 mActivityManager.unbindBackupAgent(app);
3003
3004 // The agent was running with a stub Application object, so shut it down.
3005 // !!! We hardcode the confirmation UI's package name here rather than use a
3006 // manifest flag! TODO something less direct.
3007 if (app.uid != Process.SYSTEM_UID
3008 && !app.packageName.equals("com.android.backupconfirm")) {
3009 if (DEBUG) Slog.d(TAG, "Killing host process");
3010 mActivityManager.killApplicationProcess(app.processName, app.uid);
3011 } else {
3012 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
3013 }
3014 } catch (RemoteException e) {
3015 Slog.d(TAG, "Lost app trying to shut down");
3016 }
3017 mAgent = null;
3018 }
3019 }
3020
3021 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
3022 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07003023 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003024 int mResult;
3025
3026 public void reset() {
3027 synchronized (mDone) {
3028 mDone.set(false);
3029 }
3030 }
3031
3032 public void waitForCompletion() {
3033 synchronized (mDone) {
3034 while (mDone.get() == false) {
3035 try {
3036 mDone.wait();
3037 } catch (InterruptedException e) { }
3038 }
3039 }
3040 }
3041
3042 int getResult() {
3043 return mResult;
3044 }
3045
3046 @Override
3047 public void packageInstalled(String packageName, int returnCode)
3048 throws RemoteException {
3049 synchronized (mDone) {
3050 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07003051 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07003052 mDone.set(true);
3053 mDone.notifyAll();
3054 }
3055 }
3056 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003057
3058 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
3059 final AtomicBoolean mDone = new AtomicBoolean();
3060 int mResult;
3061
3062 public void reset() {
3063 synchronized (mDone) {
3064 mDone.set(false);
3065 }
3066 }
3067
3068 public void waitForCompletion() {
3069 synchronized (mDone) {
3070 while (mDone.get() == false) {
3071 try {
3072 mDone.wait();
3073 } catch (InterruptedException e) { }
3074 }
3075 }
3076 }
3077
3078 @Override
3079 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
3080 synchronized (mDone) {
3081 mResult = returnCode;
3082 mDone.set(true);
3083 mDone.notifyAll();
3084 }
3085 }
3086 }
3087
Christopher Tate75a99702011-05-18 16:28:19 -07003088 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07003089 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07003090
3091 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
3092 boolean okay = true;
3093
3094 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
3095
3096 // The file content is an .apk file. Copy it out to a staging location and
3097 // attempt to install it.
3098 File apkFile = new File(mDataDir, info.packageName);
3099 try {
3100 FileOutputStream apkStream = new FileOutputStream(apkFile);
3101 byte[] buffer = new byte[32 * 1024];
3102 long size = info.size;
3103 while (size > 0) {
3104 long toRead = (buffer.length < size) ? buffer.length : size;
3105 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003106 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003107 apkStream.write(buffer, 0, didRead);
3108 size -= didRead;
3109 }
3110 apkStream.close();
3111
3112 // make sure the installer can read it
3113 apkFile.setReadable(true, false);
3114
3115 // Now install it
3116 Uri packageUri = Uri.fromFile(apkFile);
3117 mInstallObserver.reset();
3118 mPackageManager.installPackage(packageUri, mInstallObserver,
3119 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
3120 mInstallObserver.waitForCompletion();
3121
3122 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
3123 // The only time we continue to accept install of data even if the
3124 // apk install failed is if we had already determined that we could
3125 // accept the data regardless.
3126 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
3127 okay = false;
3128 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003129 } else {
3130 // Okay, the install succeeded. Make sure it was the right app.
3131 boolean uninstall = false;
3132 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
3133 Slog.w(TAG, "Restore stream claimed to include apk for "
3134 + info.packageName + " but apk was really "
3135 + mInstallObserver.mPackageName);
3136 // delete the package we just put in place; it might be fraudulent
3137 okay = false;
3138 uninstall = true;
3139 } else {
3140 try {
3141 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
3142 PackageManager.GET_SIGNATURES);
3143 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
3144 Slog.w(TAG, "Restore stream contains apk of package "
3145 + info.packageName + " but it disallows backup/restore");
3146 okay = false;
3147 } else {
3148 // So far so good -- do the signatures match the manifest?
3149 Signature[] sigs = mManifestSignatures.get(info.packageName);
3150 if (!signaturesMatch(sigs, pkg)) {
3151 Slog.w(TAG, "Installed app " + info.packageName
3152 + " signatures do not match restore manifest");
3153 okay = false;
3154 uninstall = true;
3155 }
3156 }
3157 } catch (NameNotFoundException e) {
3158 Slog.w(TAG, "Install of package " + info.packageName
3159 + " succeeded but now not found");
3160 okay = false;
3161 }
3162 }
3163
3164 // If we're not okay at this point, we need to delete the package
3165 // that we just installed.
3166 if (uninstall) {
3167 mDeleteObserver.reset();
3168 mPackageManager.deletePackage(mInstallObserver.mPackageName,
3169 mDeleteObserver, 0);
3170 mDeleteObserver.waitForCompletion();
3171 }
Christopher Tate75a99702011-05-18 16:28:19 -07003172 }
3173 } catch (IOException e) {
3174 Slog.e(TAG, "Unable to transcribe restored apk for install");
3175 okay = false;
3176 } finally {
3177 apkFile.delete();
3178 }
3179
3180 return okay;
3181 }
3182
3183 // Given an actual file content size, consume the post-content padding mandated
3184 // by the tar format.
3185 void skipTarPadding(long size, InputStream instream) throws IOException {
3186 long partial = (size + 512) % 512;
3187 if (partial > 0) {
3188 byte[] buffer = new byte[512];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003189 int nRead = instream.read(buffer, 0, 512 - (int)partial);
3190 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003191 }
3192 }
3193
3194 // Returns a policy constant; takes a buffer arg to reduce memory churn
3195 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
3196 throws IOException {
3197 // Fail on suspiciously large manifest files
3198 if (info.size > 64 * 1024) {
3199 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
3200 }
3201 byte[] buffer = new byte[(int) info.size];
3202 int nRead = 0;
3203 while (nRead < info.size) {
3204 nRead += instream.read(buffer, nRead, (int)info.size - nRead);
3205 }
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003206 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003207
3208 RestorePolicy policy = RestorePolicy.IGNORE;
3209 String[] str = new String[1];
3210 int offset = 0;
3211
3212 try {
3213 offset = extractLine(buffer, offset, str);
3214 int version = Integer.parseInt(str[0]);
3215 if (version == BACKUP_MANIFEST_VERSION) {
3216 offset = extractLine(buffer, offset, str);
3217 String manifestPackage = str[0];
3218 // TODO: handle <original-package>
3219 if (manifestPackage.equals(info.packageName)) {
3220 offset = extractLine(buffer, offset, str);
3221 version = Integer.parseInt(str[0]); // app version
3222 offset = extractLine(buffer, offset, str);
3223 int platformVersion = Integer.parseInt(str[0]);
3224 offset = extractLine(buffer, offset, str);
3225 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
3226 offset = extractLine(buffer, offset, str);
3227 boolean hasApk = str[0].equals("1");
3228 offset = extractLine(buffer, offset, str);
3229 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07003230 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07003231 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07003232 for (int i = 0; i < numSigs; i++) {
3233 offset = extractLine(buffer, offset, str);
3234 sigs[i] = new Signature(str[0]);
3235 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003236 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07003237
3238 // Okay, got the manifest info we need...
3239 try {
Christopher Tate75a99702011-05-18 16:28:19 -07003240 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3241 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07003242 // Fall through to IGNORE if the app explicitly disallows backup
3243 final int flags = pkgInfo.applicationInfo.flags;
3244 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
3245 // Verify signatures against any installed version; if they
3246 // don't match, then we fall though and ignore the data. The
3247 // signatureMatch() method explicitly ignores the signature
3248 // check for packages installed on the system partition, because
3249 // such packages are signed with the platform cert instead of
3250 // the app developer's cert, so they're different on every
3251 // device.
3252 if (signaturesMatch(sigs, pkgInfo)) {
3253 if (pkgInfo.versionCode >= version) {
3254 Slog.i(TAG, "Sig + version match; taking data");
3255 policy = RestorePolicy.ACCEPT;
3256 } else {
3257 // The data is from a newer version of the app than
3258 // is presently installed. That means we can only
3259 // use it if the matching apk is also supplied.
3260 Slog.d(TAG, "Data version " + version
3261 + " is newer than installed version "
3262 + pkgInfo.versionCode + " - requiring apk");
3263 policy = RestorePolicy.ACCEPT_IF_APK;
3264 }
Christopher Tate75a99702011-05-18 16:28:19 -07003265 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07003266 Slog.w(TAG, "Restore manifest signatures do not match "
3267 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07003268 }
Christopher Tatea858cb02011-06-03 12:27:51 -07003269 } else {
3270 if (DEBUG) Slog.i(TAG, "Restore manifest from "
3271 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07003272 }
3273 } catch (NameNotFoundException e) {
3274 // Okay, the target app isn't installed. We can process
3275 // the restore properly only if the dataset provides the
3276 // apk file and we can successfully install it.
3277 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
3278 + " not installed; requiring apk in dataset");
3279 policy = RestorePolicy.ACCEPT_IF_APK;
3280 }
3281
3282 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
3283 Slog.i(TAG, "Cannot restore package " + info.packageName
3284 + " without the matching .apk");
3285 }
3286 } else {
3287 Slog.i(TAG, "Missing signature on backed-up package "
3288 + info.packageName);
3289 }
3290 } else {
3291 Slog.i(TAG, "Expected package " + info.packageName
3292 + " but restore manifest claims " + manifestPackage);
3293 }
3294 } else {
3295 Slog.i(TAG, "Unknown restore manifest version " + version
3296 + " for package " + info.packageName);
3297 }
3298 } catch (NumberFormatException e) {
3299 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
3300 }
3301
3302 return policy;
3303 }
3304
3305 // Builds a line from a byte buffer starting at 'offset', and returns
3306 // the index of the next unconsumed data in the buffer.
3307 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
3308 final int end = buffer.length;
3309 if (offset >= end) throw new IOException("Incomplete data");
3310
3311 int pos;
3312 for (pos = offset; pos < end; pos++) {
3313 byte c = buffer[pos];
3314 // at LF we declare end of line, and return the next char as the
3315 // starting point for the next time through
3316 if (c == '\n') {
3317 break;
3318 }
3319 }
3320 outStr[0] = new String(buffer, offset, pos - offset);
3321 pos++; // may be pointing an extra byte past the end but that's okay
3322 return pos;
3323 }
3324
3325 void dumpFileMetadata(FileMetadata info) {
3326 if (DEBUG) {
3327 StringBuilder b = new StringBuilder(128);
3328
3329 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07003330 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07003331 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
3332 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
3333 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
3334 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
3335 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
3336 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
3337 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
3338 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
3339 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
3340 b.append(String.format(" %9d ", info.size));
3341
3342 Date stamp = new Date(info.mtime);
3343 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
3344
3345 b.append(info.packageName);
3346 b.append(" :: ");
3347 b.append(info.domain);
3348 b.append(" :: ");
3349 b.append(info.path);
3350
3351 Slog.i(TAG, b.toString());
3352 }
3353 }
3354 // Consume a tar file header block [sequence] and accumulate the relevant metadata
3355 FileMetadata readTarHeaders(InputStream instream) throws IOException {
3356 byte[] block = new byte[512];
3357 FileMetadata info = null;
3358
3359 boolean gotHeader = readTarHeader(instream, block);
3360 if (gotHeader) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003361 try {
3362 // okay, presume we're okay, and extract the various metadata
3363 info = new FileMetadata();
3364 info.size = extractRadix(block, 124, 12, 8);
3365 info.mtime = extractRadix(block, 136, 12, 8);
3366 info.mode = extractRadix(block, 100, 8, 8);
Christopher Tate75a99702011-05-18 16:28:19 -07003367
Christopher Tate2efd2db2011-07-19 16:32:49 -07003368 info.path = extractString(block, 345, 155); // prefix
3369 String path = extractString(block, 0, 100);
3370 if (path.length() > 0) {
3371 if (info.path.length() > 0) info.path += '/';
3372 info.path += path;
Christopher Tate75a99702011-05-18 16:28:19 -07003373 }
Christopher Tate75a99702011-05-18 16:28:19 -07003374
Christopher Tate2efd2db2011-07-19 16:32:49 -07003375 // tar link indicator field: 1 byte at offset 156 in the header.
3376 int typeChar = block[156];
3377 if (typeChar == 'x') {
3378 // pax extended header, so we need to read that
3379 gotHeader = readPaxExtendedHeader(instream, info);
3380 if (gotHeader) {
3381 // and after a pax extended header comes another real header -- read
3382 // that to find the real file type
3383 gotHeader = readTarHeader(instream, block);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003384 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003385 if (!gotHeader) throw new IOException("Bad or missing pax header");
3386
3387 typeChar = block[156];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003388 }
Christopher Tate75a99702011-05-18 16:28:19 -07003389
Christopher Tate2efd2db2011-07-19 16:32:49 -07003390 switch (typeChar) {
3391 case '0': info.type = BackupAgent.TYPE_FILE; break;
3392 case '5': {
3393 info.type = BackupAgent.TYPE_DIRECTORY;
3394 if (info.size != 0) {
3395 Slog.w(TAG, "Directory entry with nonzero size in header");
3396 info.size = 0;
3397 }
3398 break;
Christopher Tate75a99702011-05-18 16:28:19 -07003399 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003400 case 0: {
3401 // presume EOF
3402 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
3403 return null;
3404 }
3405 default: {
3406 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
3407 throw new IOException("Unknown entity type " + typeChar);
3408 }
Christopher Tate75a99702011-05-18 16:28:19 -07003409 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003410
3411 // Parse out the path
3412 //
3413 // first: apps/shared/unrecognized
3414 if (FullBackup.SHARED_PREFIX.regionMatches(0,
3415 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
3416 // File in shared storage. !!! TODO: implement this.
3417 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
3418 info.packageName = "com.android.sharedstoragebackup";
3419 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
3420 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
3421 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
3422 info.path, 0, FullBackup.APPS_PREFIX.length())) {
3423 // App content! Parse out the package name and domain
3424
3425 // strip the apps/ prefix
3426 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
3427
3428 // extract the package name
3429 int slash = info.path.indexOf('/');
3430 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3431 info.packageName = info.path.substring(0, slash);
3432 info.path = info.path.substring(slash+1);
3433
3434 // if it's a manifest we're done, otherwise parse out the domains
3435 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3436 slash = info.path.indexOf('/');
3437 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3438 info.domain = info.path.substring(0, slash);
3439 // validate that it's one of the domains we understand
3440 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3441 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3442 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3443 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3444 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3445 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3446 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3447 throw new IOException("Unrecognized domain " + info.domain);
3448 }
3449
3450 info.path = info.path.substring(slash + 1);
3451 }
3452 }
3453 } catch (IOException e) {
3454 if (DEBUG) {
3455 Slog.e(TAG, "Parse error in header. Hexdump:");
3456 HEXLOG(block);
3457 }
3458 throw e;
Christopher Tate75a99702011-05-18 16:28:19 -07003459 }
3460 }
3461 return info;
3462 }
3463
Christopher Tate2efd2db2011-07-19 16:32:49 -07003464 private void HEXLOG(byte[] block) {
3465 int offset = 0;
3466 int todo = block.length;
3467 StringBuilder buf = new StringBuilder(64);
3468 while (todo > 0) {
3469 buf.append(String.format("%04x ", offset));
3470 int numThisLine = (todo > 16) ? 16 : todo;
3471 for (int i = 0; i < numThisLine; i++) {
3472 buf.append(String.format("%02x ", block[offset+i]));
3473 }
3474 Slog.i("hexdump", buf.toString());
3475 buf.setLength(0);
3476 todo -= numThisLine;
3477 offset += numThisLine;
Christopher Tate75a99702011-05-18 16:28:19 -07003478 }
Christopher Tate2efd2db2011-07-19 16:32:49 -07003479 }
3480
3481 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3482 int totalRead = 0;
3483 while (totalRead < 512) {
3484 int nRead = instream.read(block, totalRead, 512 - totalRead);
3485 if (nRead >= 0) {
3486 mBytes += nRead;
3487 totalRead += nRead;
3488 } else {
3489 if (totalRead == 0) {
3490 // EOF instead of a new header; we're done
3491 break;
3492 }
3493 throw new IOException("Unable to read full block header, t=" + totalRead);
3494 }
3495 }
3496 return (totalRead == 512);
Christopher Tate75a99702011-05-18 16:28:19 -07003497 }
3498
3499 // overwrites 'info' fields based on the pax extended header
3500 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3501 throws IOException {
3502 // We should never see a pax extended header larger than this
3503 if (info.size > 32*1024) {
3504 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3505 + " - aborting");
3506 throw new IOException("Sanity failure: pax header size " + info.size);
3507 }
3508
3509 // read whole blocks, not just the content size
3510 int numBlocks = (int)((info.size + 511) >> 9);
3511 byte[] data = new byte[numBlocks * 512];
3512 int nRead = instream.read(data);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003513 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003514 if (nRead != data.length) {
3515 return false;
3516 }
3517
3518 final int contentSize = (int) info.size;
3519 int offset = 0;
3520 do {
3521 // extract the line at 'offset'
3522 int eol = offset+1;
3523 while (eol < contentSize && data[eol] != ' ') eol++;
3524 if (eol >= contentSize) {
3525 // error: we just hit EOD looking for the end of the size field
3526 throw new IOException("Invalid pax data");
3527 }
3528 // eol points to the space between the count and the key
3529 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3530 int key = eol + 1; // start of key=value
3531 eol = offset + linelen - 1; // trailing LF
3532 int value;
3533 for (value = key+1; data[value] != '=' && value <= eol; value++);
3534 if (value > eol) {
3535 throw new IOException("Invalid pax declaration");
3536 }
3537
3538 // pax requires that key/value strings be in UTF-8
3539 String keyStr = new String(data, key, value-key, "UTF-8");
3540 // -1 to strip the trailing LF
3541 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3542
3543 if ("path".equals(keyStr)) {
3544 info.path = valStr;
3545 } else if ("size".equals(keyStr)) {
3546 info.size = Long.parseLong(valStr);
3547 } else {
3548 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3549 }
3550
3551 offset += linelen;
3552 } while (offset < contentSize);
3553
3554 return true;
3555 }
3556
3557 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3558 throws IOException {
3559 long value = 0;
3560 final int end = offset + maxChars;
3561 for (int i = offset; i < end; i++) {
3562 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003563 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003564 if (b == 0 || b == ' ') break;
3565 if (b < '0' || b > ('0' + radix - 1)) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07003566 throw new IOException("Invalid number in header: '" + (char)b + "' for radix " + radix);
Christopher Tate75a99702011-05-18 16:28:19 -07003567 }
3568 value = radix * value + (b - '0');
3569 }
3570 return value;
3571 }
3572
3573 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3574 final int end = offset + maxChars;
3575 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003576 // tar string fields terminate early with a NUL
3577 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003578 return new String(data, offset, eos-offset, "US-ASCII");
3579 }
3580
3581 void sendStartRestore() {
3582 if (mObserver != null) {
3583 try {
3584 mObserver.onStartRestore();
3585 } catch (RemoteException e) {
3586 Slog.w(TAG, "full restore observer went away: startRestore");
3587 mObserver = null;
3588 }
3589 }
3590 }
3591
3592 void sendOnRestorePackage(String name) {
3593 if (mObserver != null) {
3594 try {
3595 // TODO: use a more user-friendly name string
3596 mObserver.onRestorePackage(name);
3597 } catch (RemoteException e) {
3598 Slog.w(TAG, "full restore observer went away: restorePackage");
3599 mObserver = null;
3600 }
3601 }
3602 }
3603
3604 void sendEndRestore() {
3605 if (mObserver != null) {
3606 try {
3607 mObserver.onEndRestore();
3608 } catch (RemoteException e) {
3609 Slog.w(TAG, "full restore observer went away: endRestore");
3610 mObserver = null;
3611 }
3612 }
3613 }
3614 }
3615
Christopher Tatedf01dea2009-06-09 20:45:02 -07003616 // ----- Restore handling -----
3617
Christopher Tate78dd4a72009-11-04 11:49:08 -08003618 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3619 // If the target resides on the system partition, we allow it to restore
3620 // data from the like-named package in a restore set even if the signatures
3621 // do not match. (Unlike general applications, those flashed to the system
3622 // partition will be signed with the device's platform certificate, so on
3623 // different phones the same system app will have different signatures.)
3624 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003625 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003626 return true;
3627 }
3628
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003629 // Allow unsigned apps, but not signed on one device and unsigned on the other
3630 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003631 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003632 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003633 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003634 if ((storedSigs == null || storedSigs.length == 0)
3635 && (deviceSigs == null || deviceSigs.length == 0)) {
3636 return true;
3637 }
3638 if (storedSigs == null || deviceSigs == null) {
3639 return false;
3640 }
3641
Christopher Tateabce4e82009-06-18 18:35:32 -07003642 // !!! TODO: this demands that every stored signature match one
3643 // that is present on device, and does not demand the converse.
3644 // Is this this right policy?
3645 int nStored = storedSigs.length;
3646 int nDevice = deviceSigs.length;
3647
3648 for (int i=0; i < nStored; i++) {
3649 boolean match = false;
3650 for (int j=0; j < nDevice; j++) {
3651 if (storedSigs[i].equals(deviceSigs[j])) {
3652 match = true;
3653 break;
3654 }
3655 }
3656 if (!match) {
3657 return false;
3658 }
3659 }
3660 return true;
3661 }
3662
Christopher Tate44a27902010-01-27 17:15:49 -08003663 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003664 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003665 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003666 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003667 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003668 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003669 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003670 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003671 private HashSet<String> mFilterSet;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003672
Christopher Tate5cbbf562009-06-22 16:44:51 -07003673 class RestoreRequest {
3674 public PackageInfo app;
3675 public int storedAppVersion;
3676
3677 RestoreRequest(PackageInfo _app, int _version) {
3678 app = _app;
3679 storedAppVersion = _version;
3680 }
3681 }
3682
Christopher Tate44a27902010-01-27 17:15:49 -08003683 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003684 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003685 boolean needFullBackup, String[] filterSet) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003686 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003687 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003688 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003689 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003690 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003691 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003692
Christopher Tate284f1bb2011-07-07 14:31:18 -07003693 if (filterSet != null) {
3694 mFilterSet = new HashSet<String>();
3695 for (String pkg : filterSet) {
3696 mFilterSet.add(pkg);
3697 }
3698 } else {
3699 mFilterSet = null;
3700 }
3701
Christopher Tate5cb400b2009-06-25 16:03:14 -07003702 try {
3703 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3704 } catch (RemoteException e) {
3705 // can't happen; the transport is local
3706 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003707 }
3708
Christopher Tatedf01dea2009-06-09 20:45:02 -07003709 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003710 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003711 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08003712 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate284f1bb2011-07-07 14:31:18 -07003713 + " mTargetPackage=" + mTargetPackage + " mFilterSet=" + mFilterSet
3714 + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003715
Christopher Tateb49ceb32010-02-08 16:22:24 -08003716 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003717 int error = -1; // assume error
3718
Dan Egnorefe52642009-06-24 00:16:33 -07003719 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07003720 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003721 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003722 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07003723
Dan Egnorefe52642009-06-24 00:16:33 -07003724 // Get the list of all packages which have backup enabled.
3725 // (Include the Package Manager metadata pseudo-package first.)
3726 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
3727 PackageInfo omPackage = new PackageInfo();
3728 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
3729 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003730
Dan Egnorefe52642009-06-24 00:16:33 -07003731 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003732 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07003733 // if there's a filter set, strip out anything that isn't
3734 // present before proceeding
3735 if (mFilterSet != null) {
3736 for (int i = agentPackages.size() - 1; i >= 0; i--) {
3737 final PackageInfo pkg = agentPackages.get(i);
3738 if (! mFilterSet.contains(pkg.packageName)) {
3739 agentPackages.remove(i);
3740 }
3741 }
3742 if (DEBUG) {
3743 Slog.i(TAG, "Post-filter package set for restore:");
3744 for (PackageInfo p : agentPackages) {
3745 Slog.i(TAG, " " + p);
3746 }
3747 }
3748 }
Christopher Tate84725812010-02-04 15:52:40 -08003749 restorePackages.addAll(agentPackages);
3750 } else {
3751 // Just one package to attempt restore of
3752 restorePackages.add(mTargetPackage);
3753 }
Dan Egnorefe52642009-06-24 00:16:33 -07003754
Christopher Tate7d562ec2009-06-25 18:03:43 -07003755 // let the observer know that we're running
3756 if (mObserver != null) {
3757 try {
3758 // !!! TODO: get an actual count from the transport after
3759 // its startRestore() runs?
3760 mObserver.restoreStarting(restorePackages.size());
3761 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003762 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003763 mObserver = null;
3764 }
3765 }
3766
Dan Egnor01445162009-09-21 17:04:05 -07003767 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
3768 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003769 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003770 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003771 return;
3772 }
3773
3774 String packageName = mTransport.nextRestorePackage();
3775 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003776 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003777 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003778 return;
3779 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003780 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003781 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003782 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07003783 return;
3784 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003785 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07003786 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003787 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003788 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003789 return;
3790 }
3791
3792 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08003793 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07003794 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07003795 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
3796 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07003797
Christopher Tate8c032472009-07-02 14:28:47 -07003798 // Verify that the backup set includes metadata. If not, we can't do
3799 // signature/version verification etc, so we simply do not proceed with
3800 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07003801 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003802 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003803 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003804 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07003805 return;
3806 }
3807
Christopher Tate7d562ec2009-06-25 18:03:43 -07003808 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07003809 for (;;) {
3810 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003811
Dan Egnorefe52642009-06-24 00:16:33 -07003812 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003813 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003814 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003815 return;
3816 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003817 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07003818 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003819 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003820
Christopher Tate7d562ec2009-06-25 18:03:43 -07003821 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07003822 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07003823 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07003824 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003825 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003826 mObserver = null;
3827 }
3828 }
3829
Dan Egnorefe52642009-06-24 00:16:33 -07003830 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
3831 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003832 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003833 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003834 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003835 continue;
3836 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003837
Dan Egnorbb9001c2009-07-27 12:20:13 -07003838 PackageInfo packageInfo;
3839 try {
3840 int flags = PackageManager.GET_SIGNATURES;
3841 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
3842 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003843 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003844 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003845 "Package missing on device");
3846 continue;
3847 }
3848
Dan Egnorefe52642009-06-24 00:16:33 -07003849 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08003850 // Data is from a "newer" version of the app than we have currently
3851 // installed. If the app has not declared that it is prepared to
3852 // handle this case, we do not attempt the restore.
3853 if ((packageInfo.applicationInfo.flags
3854 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
3855 String message = "Version " + metaInfo.versionCode
3856 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003857 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08003858 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
3859 packageName, message);
3860 continue;
3861 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003862 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08003863 + " > installed " + packageInfo.versionCode
3864 + " but restoreAnyVersion");
3865 }
Dan Egnorefe52642009-06-24 00:16:33 -07003866 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003867
Christopher Tate78dd4a72009-11-04 11:49:08 -08003868 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003869 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003870 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003871 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07003872 continue;
3873 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003874
Joe Onorato8a9b2202010-02-26 18:56:32 -08003875 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07003876 + " restore version [" + metaInfo.versionCode
3877 + "] is compatible with installed version ["
3878 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07003879
Christopher Tate3de55bc2010-03-12 17:28:08 -08003880 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07003881 IBackupAgent agent = bindToAgentSynchronous(
3882 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08003883 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07003884 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003885 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003886 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003887 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003888 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003889 }
3890
Christopher Tate5e1ab332009-09-01 20:32:49 -07003891 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07003892 try {
Chris Tate249345b2010-10-29 12:57:04 -07003893 processOneRestore(packageInfo, metaInfo.versionCode, agent,
3894 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003895 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07003896 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003897 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07003898 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07003899
3900 // The agent was probably running with a stub Application object,
3901 // which isn't a valid run mode for the main app logic. Shut
3902 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08003903 // usual full initialization. Note that this is only done for
3904 // full-system restores: when a single app has requested a restore,
3905 // it is explicitly not killed following that operation.
3906 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07003907 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003908 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003909 + packageInfo.applicationInfo.processName);
3910 mActivityManager.killApplicationProcess(
3911 packageInfo.applicationInfo.processName,
3912 packageInfo.applicationInfo.uid);
3913 }
Dan Egnorefe52642009-06-24 00:16:33 -07003914 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003915 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003916
3917 // if we get this far, report success to the observer
3918 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07003919 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003920 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003921 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003922 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003923 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003924 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003925
Dan Egnorefe52642009-06-24 00:16:33 -07003926 try {
3927 mTransport.finishRestore();
3928 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003929 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003930 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003931
3932 if (mObserver != null) {
3933 try {
3934 mObserver.restoreFinished(error);
3935 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003936 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003937 }
3938 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003939
Christopher Tate84725812010-02-04 15:52:40 -08003940 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08003941 // ancestral dataset, as well as the set of apps that are possibly
3942 // restoreable from the dataset
3943 if (mTargetPackage == null && pmAgent != null) {
3944 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003945 mAncestralToken = mToken;
3946 writeRestoreTokens();
3947 }
3948
Christopher Tate1bb69062010-02-19 17:02:12 -08003949 // We must under all circumstances tell the Package Manager to
3950 // proceed with install notifications if it's waiting for us.
3951 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003952 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08003953 try {
3954 mPackageManagerBinder.finishPackageInstall(mPmToken);
3955 } catch (RemoteException e) { /* can't happen */ }
3956 }
3957
Christopher Tate73a3cb32010-12-13 18:27:26 -08003958 // Furthermore we need to reset the session timeout clock
3959 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3960 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
3961 TIMEOUT_RESTORE_INTERVAL);
3962
Christopher Tateb6787f22009-07-02 17:40:45 -07003963 // done; we can finally release the wakelock
3964 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07003965 }
3966 }
3967
Dan Egnorefe52642009-06-24 00:16:33 -07003968 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07003969 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
3970 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003971 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07003972 final String packageName = app.packageName;
3973
Joe Onorato8a9b2202010-02-26 18:56:32 -08003974 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003975
Christopher Tatec7b31e32009-06-10 15:49:30 -07003976 // !!! TODO: get the dirs from the transport
3977 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003978 File newStateName = new File(mStateDir, packageName + ".new");
3979 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003980
Dan Egnorbb9001c2009-07-27 12:20:13 -07003981 ParcelFileDescriptor backupData = null;
3982 ParcelFileDescriptor newState = null;
3983
Christopher Tate4a627c72011-04-01 14:43:32 -07003984 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003985 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07003986 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07003987 backupData = ParcelFileDescriptor.open(backupDataName,
3988 ParcelFileDescriptor.MODE_READ_WRITE |
3989 ParcelFileDescriptor.MODE_CREATE |
3990 ParcelFileDescriptor.MODE_TRUNCATE);
3991
Dan Egnor01445162009-09-21 17:04:05 -07003992 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003993 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003994 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003995 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07003996 }
3997
3998 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07003999 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07004000 backupData = ParcelFileDescriptor.open(backupDataName,
4001 ParcelFileDescriptor.MODE_READ_ONLY);
4002
Dan Egnorbb9001c2009-07-27 12:20:13 -07004003 newState = ParcelFileDescriptor.open(newStateName,
4004 ParcelFileDescriptor.MODE_READ_WRITE |
4005 ParcelFileDescriptor.MODE_CREATE |
4006 ParcelFileDescriptor.MODE_TRUNCATE);
4007
Christopher Tate44a27902010-01-27 17:15:49 -08004008 // Kick off the restore, checking for hung agents
4009 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
4010 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
4011 boolean success = waitUntilOperationComplete(token);
4012
4013 if (!success) {
4014 throw new RuntimeException("restore timeout");
4015 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004016
4017 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07004018 //
4019 // !!! TODO: the restored data should be migrated on the server
4020 // side into the current dataset. In that case the new state file
4021 // we just created would reflect the data already extant in the
4022 // backend, so there'd be nothing more to do. Until that happens,
4023 // however, we need to make sure that we record the data to the
4024 // current backend dataset. (Yes, this means shipping the data over
4025 // the wire in both directions. That's bad, but consistency comes
4026 // first, then efficiency.) Once we introduce server-side data
4027 // migration to the newly-restored device's dataset, we will change
4028 // the following from a discard of the newly-written state to the
4029 // "correct" operation of renaming into the canonical state blob.
4030 newStateName.delete(); // TODO: remove; see above comment
4031 //newStateName.renameTo(savedStateName); // TODO: replace with this
4032
Dan Egnorbb9001c2009-07-27 12:20:13 -07004033 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004034 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07004035 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004036 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004037 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07004038
Christopher Tate96733042009-07-20 14:49:13 -07004039 // If the agent fails restore, it might have put the app's data
4040 // into an incoherent state. For consistency we wipe its data
4041 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07004042 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07004043 } finally {
4044 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07004045 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
4046 try { if (newState != null) newState.close(); } catch (IOException e) {}
4047 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07004048 synchronized (mCurrentOperations) {
4049 mCurrentOperations.delete(token);
4050 }
Chris Tate249345b2010-10-29 12:57:04 -07004051
4052 // If we know a priori that we'll need to perform a full post-restore backup
4053 // pass, clear the new state file data. This means we're discarding work that
4054 // was just done by the app's agent, but this way the agent doesn't need to
4055 // take any special action based on global device state.
4056 if (needFullBackup) {
4057 newStateName.delete();
4058 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07004059 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004060 }
4061 }
4062
Christopher Tate44a27902010-01-27 17:15:49 -08004063 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004064 IBackupTransport mTransport;
4065 PackageInfo mPackage;
4066
Christopher Tate44a27902010-01-27 17:15:49 -08004067 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07004068 mTransport = transport;
4069 mPackage = packageInfo;
4070 }
4071
Christopher Tateee0e78a2009-07-02 11:17:03 -07004072 public void run() {
4073 try {
4074 // Clear the on-device backup state to ensure a full backup next time
4075 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
4076 File stateFile = new File(stateDir, mPackage.packageName);
4077 stateFile.delete();
4078
4079 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07004080 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004081 mTransport.clearBackupData(mPackage);
4082 } catch (RemoteException e) {
4083 // can't happen; the transport is local
4084 } finally {
4085 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07004086 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07004087 mTransport.finishBackup();
4088 } catch (RemoteException e) {
4089 // can't happen; the transport is local
4090 }
Christopher Tateb6787f22009-07-02 17:40:45 -07004091
4092 // Last but not least, release the cpu
4093 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004094 }
4095 }
4096 }
4097
Christopher Tate44a27902010-01-27 17:15:49 -08004098 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004099 HashSet<String> mQueue;
4100
Christopher Tate44a27902010-01-27 17:15:49 -08004101 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004102 mQueue = transportNames;
4103 }
4104
Christopher Tate4cc86e12009-09-21 19:36:51 -07004105 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07004106 try {
4107 for (String transportName : mQueue) {
4108 IBackupTransport transport = getTransport(transportName);
4109 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004110 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004111 continue;
4112 }
4113
Joe Onorato8a9b2202010-02-26 18:56:32 -08004114 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004115 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07004116 long startRealtime = SystemClock.elapsedRealtime();
4117 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07004118
Christopher Tate4cc86e12009-09-21 19:36:51 -07004119 if (status == BackupConstants.TRANSPORT_OK) {
4120 status = transport.finishBackup();
4121 }
4122
4123 // Okay, the wipe really happened. Clean up our local bookkeeping.
4124 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004125 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07004126 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004127 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07004128 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004129 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004130 synchronized (mQueueLock) {
4131 recordInitPendingLocked(false, transportName);
4132 }
Dan Egnor726247c2009-09-29 19:12:31 -07004133 } else {
4134 // If this didn't work, requeue this one and try again
4135 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08004136 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004137 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004138 synchronized (mQueueLock) {
4139 recordInitPendingLocked(true, transportName);
4140 }
4141 // do this via another alarm to make sure of the wakelock states
4142 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004143 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07004144 + transportName + " resched in " + delay);
4145 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
4146 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004147 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07004148 }
4149 } catch (RemoteException e) {
4150 // can't happen; the transports are local
4151 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004152 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004153 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08004154 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07004155 mWakelock.release();
4156 }
4157 }
4158 }
4159
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004160 private void dataChangedImpl(String packageName) {
4161 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4162 dataChangedImpl(packageName, targets);
4163 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07004164
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004165 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07004166 // Record that we need a backup pass for the caller. Since multiple callers
4167 // may share a uid, we need to note all candidates within that uid and schedule
4168 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004169 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004170
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004171 if (targets == null) {
4172 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4173 + " uid=" + Binder.getCallingUid());
4174 return;
4175 }
4176
4177 synchronized (mQueueLock) {
4178 // Note that this client has made data changes that need to be backed up
4179 for (ApplicationInfo app : targets) {
4180 // validate the caller-supplied package name against the known set of
4181 // packages associated with this uid
4182 if (app.packageName.equals(packageName)) {
4183 // Add the caller to the set of pending backups. If there is
4184 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07004185 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08004186 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004187 // Journal this request in case of crash. The put()
4188 // operation returned null when this package was not already
4189 // in the set; we want to avoid touching the disk redundantly.
4190 writeToJournalLocked(packageName);
4191
4192 if (DEBUG) {
4193 int numKeys = mPendingBackups.size();
4194 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
4195 for (BackupRequest b : mPendingBackups.values()) {
4196 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
4197 }
4198 }
4199 }
4200 }
4201 }
4202 }
4203 }
4204
4205 // Note: packageName is currently unused, but may be in the future
4206 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07004207 // If the caller does not hold the BACKUP permission, it can only request a
4208 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07004209 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07004210 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004211 synchronized (mBackupParticipants) {
4212 return mBackupParticipants.get(Binder.getCallingUid());
4213 }
4214 }
4215
4216 // a caller with full permission can ask to back up any participating app
4217 // !!! TODO: allow backup of ANY app?
4218 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
4219 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07004220 int N = mBackupParticipants.size();
4221 for (int i = 0; i < N; i++) {
4222 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4223 if (s != null) {
4224 targets.addAll(s);
4225 }
4226 }
4227 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004228 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07004229 }
Christopher Tate46758122009-05-06 11:22:00 -07004230
Christopher Tatecde87f42009-06-12 12:55:53 -07004231 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004232 RandomAccessFile out = null;
4233 try {
4234 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
4235 out = new RandomAccessFile(mJournal, "rws");
4236 out.seek(out.length());
4237 out.writeUTF(str);
4238 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004239 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004240 mJournal = null;
4241 } finally {
4242 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07004243 }
4244 }
4245
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07004246 // ----- IBackupManager binder interface -----
4247
4248 public void dataChanged(final String packageName) {
4249 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
4250 if (targets == null) {
4251 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
4252 + " uid=" + Binder.getCallingUid());
4253 return;
4254 }
4255
4256 mBackupHandler.post(new Runnable() {
4257 public void run() {
4258 dataChangedImpl(packageName, targets);
4259 }
4260 });
4261 }
4262
Christopher Tateee0e78a2009-07-02 11:17:03 -07004263 // Clear the given package's backup data from the current transport
4264 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004265 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004266 PackageInfo info;
4267 try {
4268 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
4269 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004270 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004271 return;
4272 }
4273
4274 // If the caller does not hold the BACKUP permission, it can only request a
4275 // wipe of its own backed-up data.
4276 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004277 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07004278 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
4279 apps = mBackupParticipants.get(Binder.getCallingUid());
4280 } else {
4281 // a caller with full permission can ask to back up any participating app
4282 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08004283 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004284 apps = new HashSet<ApplicationInfo>();
4285 int N = mBackupParticipants.size();
4286 for (int i = 0; i < N; i++) {
4287 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
4288 if (s != null) {
4289 apps.addAll(s);
4290 }
4291 }
4292 }
4293
4294 // now find the given package in the set of candidate apps
4295 for (ApplicationInfo app : apps) {
4296 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004297 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07004298 // found it; fire off the clear request
4299 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07004300 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07004301 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07004302 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
4303 new ClearParams(getTransport(mCurrentTransport), info));
4304 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07004305 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07004306 }
4307 break;
4308 }
4309 }
4310 }
4311
Christopher Tateace7f092009-06-15 18:07:25 -07004312 // Run a backup pass immediately for any applications that have declared
4313 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07004314 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04004315 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07004316
Joe Onorato8a9b2202010-02-26 18:56:32 -08004317 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07004318 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004319 // Because the alarms we are using can jitter, and we want an *immediate*
4320 // backup pass to happen, we restart the timer beginning with "next time,"
4321 // then manually fire the backup trigger intent ourselves.
4322 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07004323 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07004324 mRunBackupIntent.send();
4325 } catch (PendingIntent.CanceledException e) {
4326 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08004327 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07004328 }
Christopher Tate46758122009-05-06 11:22:00 -07004329 }
4330 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004331
Christopher Tate4a627c72011-04-01 14:43:32 -07004332 // Run a *full* backup pass for the given package, writing the resulting data stream
4333 // to the supplied file descriptor. This method is synchronous and does not return
4334 // to the caller until the backup has been completed.
4335 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
4336 boolean doAllApps, String[] pkgList) {
4337 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4338
4339 // Validate
4340 if (!doAllApps) {
4341 if (!includeShared) {
4342 // If we're backing up shared data (sdcard or equivalent), then we can run
4343 // without any supplied app names. Otherwise, we'd be doing no work, so
4344 // report the error.
4345 if (pkgList == null || pkgList.length == 0) {
4346 throw new IllegalArgumentException(
4347 "Backup requested but neither shared nor any apps named");
4348 }
4349 }
4350 }
4351
4352 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
4353 + " shared=" + includeShared + " all=" + doAllApps
4354 + " pkgs=" + pkgList);
4355
4356 long oldId = Binder.clearCallingIdentity();
4357 try {
4358 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
4359 doAllApps, pkgList);
4360 final int token = generateToken();
4361 synchronized (mFullConfirmations) {
4362 mFullConfirmations.put(token, params);
4363 }
4364
Christopher Tate75a99702011-05-18 16:28:19 -07004365 // start up the confirmation UI
4366 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
4367 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
4368 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07004369 mFullConfirmations.delete(token);
4370 return;
4371 }
Christopher Tate75a99702011-05-18 16:28:19 -07004372
4373 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07004374 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4375
4376 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07004377 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004378
4379 // wait for the backup to be performed
4380 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
4381 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07004382 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07004383 try {
4384 fd.close();
4385 } catch (IOException e) {
4386 // just eat it
4387 }
Christopher Tate75a99702011-05-18 16:28:19 -07004388 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07004389 }
Christopher Tate75a99702011-05-18 16:28:19 -07004390 if (DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
4391 }
4392
4393 public void fullRestore(ParcelFileDescriptor fd) {
Christopher Tate2efd2db2011-07-19 16:32:49 -07004394 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullRestore");
Christopher Tate75a99702011-05-18 16:28:19 -07004395 Slog.i(TAG, "Beginning full restore...");
4396
4397 long oldId = Binder.clearCallingIdentity();
4398
4399 try {
4400 FullRestoreParams params = new FullRestoreParams(fd);
4401 final int token = generateToken();
4402 synchronized (mFullConfirmations) {
4403 mFullConfirmations.put(token, params);
4404 }
4405
4406 // start up the confirmation UI
4407 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
4408 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
4409 Slog.e(TAG, "Unable to launch full restore confirmation");
4410 mFullConfirmations.delete(token);
4411 return;
4412 }
4413
4414 // make sure the screen is lit for the user interaction
4415 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4416
4417 // start the confirmation countdown
4418 startConfirmationTimeout(token, params);
4419
4420 // wait for the restore to be performed
4421 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
4422 waitForCompletion(params);
4423 } finally {
4424 try {
4425 fd.close();
4426 } catch (IOException e) {
4427 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
4428 }
4429 Binder.restoreCallingIdentity(oldId);
4430 Slog.i(TAG, "Full restore completed");
4431 }
4432 }
4433
4434 boolean startConfirmationUi(int token, String action) {
4435 try {
4436 Intent confIntent = new Intent(action);
4437 confIntent.setClassName("com.android.backupconfirm",
4438 "com.android.backupconfirm.BackupRestoreConfirmation");
4439 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
4440 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4441 mContext.startActivity(confIntent);
4442 } catch (ActivityNotFoundException e) {
4443 return false;
4444 }
4445 return true;
4446 }
4447
4448 void startConfirmationTimeout(int token, FullParams params) {
4449 if (DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
4450 + TIMEOUT_FULL_CONFIRMATION + " millis");
4451 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
4452 token, 0, params);
4453 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07004454 }
4455
4456 void waitForCompletion(FullParams params) {
4457 synchronized (params.latch) {
4458 while (params.latch.get() == false) {
4459 try {
4460 params.latch.wait();
4461 } catch (InterruptedException e) { /* never interrupted */ }
4462 }
4463 }
4464 }
4465
4466 void signalFullBackupRestoreCompletion(FullParams params) {
4467 synchronized (params.latch) {
4468 params.latch.set(true);
4469 params.latch.notifyAll();
4470 }
4471 }
4472
4473 // Confirm that the previously-requested full backup/restore operation can proceed. This
4474 // is used to require a user-facing disclosure about the operation.
Christopher Tate2efd2db2011-07-19 16:32:49 -07004475 @Override
Christopher Tate4a627c72011-04-01 14:43:32 -07004476 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
Christopher Tate728a1c42011-07-28 18:03:03 -07004477 String curPassword, String encPpassword, IFullBackupRestoreObserver observer) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004478 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4479 + " allow=" + allow);
4480
4481 // TODO: possibly require not just this signature-only permission, but even
4482 // require that the specific designated confirmation-UI app uid is the caller?
Christopher Tate2efd2db2011-07-19 16:32:49 -07004483 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "acknowledgeFullBackupOrRestore");
Christopher Tate4a627c72011-04-01 14:43:32 -07004484
4485 long oldId = Binder.clearCallingIdentity();
4486 try {
4487
4488 FullParams params;
4489 synchronized (mFullConfirmations) {
4490 params = mFullConfirmations.get(token);
4491 if (params != null) {
4492 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4493 mFullConfirmations.delete(token);
4494
4495 if (allow) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004496 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004497 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004498 : MSG_RUN_FULL_RESTORE;
4499
Christopher Tate728a1c42011-07-28 18:03:03 -07004500 params.observer = observer;
4501 params.curPassword = curPassword;
4502 params.encryptPassword = encPpassword;
4503
Christopher Tate75a99702011-05-18 16:28:19 -07004504 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004505 mWakelock.acquire();
4506 Message msg = mBackupHandler.obtainMessage(verb, params);
4507 mBackupHandler.sendMessage(msg);
4508 } else {
4509 Slog.w(TAG, "User rejected full backup/restore operation");
4510 // indicate completion without having actually transferred any data
4511 signalFullBackupRestoreCompletion(params);
4512 }
4513 } else {
4514 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4515 }
4516 }
4517 } finally {
4518 Binder.restoreCallingIdentity(oldId);
4519 }
4520 }
4521
Christopher Tate8031a3d2009-07-06 16:36:05 -07004522 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004523 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004525 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004526
Joe Onorato8a9b2202010-02-26 18:56:32 -08004527 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004528
Christopher Tate6ef58a12009-06-29 14:56:28 -07004529 boolean wasEnabled = mEnabled;
4530 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004531 Settings.Secure.putInt(mContext.getContentResolver(),
4532 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004533 mEnabled = enable;
4534 }
4535
Christopher Tate49401dd2009-07-01 12:34:29 -07004536 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004537 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004538 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004539 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004540 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004541 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004542 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004543
Christopher Tateb6787f22009-07-02 17:40:45 -07004544 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004545
4546 // This also constitutes an opt-out, so we wipe any data for
4547 // this device from the backend. We start that process with
4548 // an alarm in order to guarantee wakelock states.
4549 if (wasEnabled && mProvisioned) {
4550 // NOTE: we currently flush every registered transport, not just
4551 // the currently-active one.
4552 HashSet<String> allTransports;
4553 synchronized (mTransports) {
4554 allTransports = new HashSet<String>(mTransports.keySet());
4555 }
4556 // build the set of transports for which we are posting an init
4557 for (String transport : allTransports) {
4558 recordInitPendingLocked(true, transport);
4559 }
4560 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4561 mRunInitIntent);
4562 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004563 }
4564 }
Christopher Tate49401dd2009-07-01 12:34:29 -07004565 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004566
Christopher Tatecce9da52010-02-03 15:11:15 -08004567 // Enable/disable automatic restore of app data at install time
4568 public void setAutoRestore(boolean doAutoRestore) {
4569 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004570 "setAutoRestore");
Christopher Tatecce9da52010-02-03 15:11:15 -08004571
Joe Onorato8a9b2202010-02-26 18:56:32 -08004572 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08004573
4574 synchronized (this) {
4575 Settings.Secure.putInt(mContext.getContentResolver(),
4576 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
4577 mAutoRestore = doAutoRestore;
4578 }
4579 }
4580
Christopher Tate8031a3d2009-07-06 16:36:05 -07004581 // Mark the backup service as having been provisioned
4582 public void setBackupProvisioned(boolean available) {
4583 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4584 "setBackupProvisioned");
4585
4586 boolean wasProvisioned = mProvisioned;
4587 synchronized (this) {
4588 Settings.Secure.putInt(mContext.getContentResolver(),
4589 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
4590 mProvisioned = available;
4591 }
4592
4593 synchronized (mQueueLock) {
4594 if (available && !wasProvisioned && mEnabled) {
4595 // we're now good to go, so start the backup alarms
4596 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
4597 } else if (!available) {
4598 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004599 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07004600 mAlarmManager.cancel(mRunBackupIntent);
4601 }
4602 }
4603 }
4604
4605 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07004606 // We used to use setInexactRepeating(), but that may be linked to
4607 // backups running at :00 more often than not, creating load spikes.
4608 // Schedule at an exact time for now, and also add a bit of "fuzz".
4609
4610 Random random = new Random();
4611 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
4612 random.nextInt(FUZZ_MILLIS);
4613 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
4614 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07004615 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07004616 }
4617
Christopher Tate6ef58a12009-06-29 14:56:28 -07004618 // Report whether the backup mechanism is currently enabled
4619 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04004620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004621 return mEnabled; // no need to synchronize just to read it
4622 }
4623
Christopher Tate91717492009-06-26 21:07:13 -07004624 // Report the name of the currently active transport
4625 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04004626 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004627 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08004628 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07004629 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07004630 }
4631
Christopher Tate91717492009-06-26 21:07:13 -07004632 // Report all known, available backup transports
4633 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07004634 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07004635
Christopher Tate91717492009-06-26 21:07:13 -07004636 String[] list = null;
4637 ArrayList<String> known = new ArrayList<String>();
4638 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
4639 if (entry.getValue() != null) {
4640 known.add(entry.getKey());
4641 }
4642 }
4643
4644 if (known.size() > 0) {
4645 list = new String[known.size()];
4646 known.toArray(list);
4647 }
4648 return list;
4649 }
4650
4651 // Select which transport to use for the next backup operation. If the given
4652 // name is not one of the available transports, no action is taken and the method
4653 // returns null.
4654 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04004655 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07004656
4657 synchronized (mTransports) {
4658 String prevTransport = null;
4659 if (mTransports.get(transport) != null) {
4660 prevTransport = mCurrentTransport;
4661 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07004662 Settings.Secure.putString(mContext.getContentResolver(),
4663 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004664 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07004665 + " returning " + prevTransport);
4666 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004667 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07004668 }
4669 return prevTransport;
4670 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004671 }
4672
Christopher Tatef5e1c292010-12-08 18:40:26 -08004673 // Supply the configuration Intent for the given transport. If the name is not one
4674 // of the available transports, or if the transport does not supply any configuration
4675 // UI, the method returns null.
4676 public Intent getConfigurationIntent(String transportName) {
4677 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4678 "getConfigurationIntent");
4679
4680 synchronized (mTransports) {
4681 final IBackupTransport transport = mTransports.get(transportName);
4682 if (transport != null) {
4683 try {
4684 final Intent intent = transport.configurationIntent();
4685 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
4686 + intent);
4687 return intent;
4688 } catch (RemoteException e) {
4689 /* fall through to return null */
4690 }
4691 }
4692 }
4693
4694 return null;
4695 }
4696
4697 // Supply the configuration summary string for the given transport. If the name is
4698 // not one of the available transports, or if the transport does not supply any
4699 // summary / destination string, the method can return null.
4700 //
4701 // This string is used VERBATIM as the summary text of the relevant Settings item!
4702 public String getDestinationString(String transportName) {
4703 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate2efd2db2011-07-19 16:32:49 -07004704 "getDestinationString");
Christopher Tatef5e1c292010-12-08 18:40:26 -08004705
4706 synchronized (mTransports) {
4707 final IBackupTransport transport = mTransports.get(transportName);
4708 if (transport != null) {
4709 try {
4710 final String text = transport.currentDestinationString();
4711 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
4712 return text;
4713 } catch (RemoteException e) {
4714 /* fall through to return null */
4715 }
4716 }
4717 }
4718
4719 return null;
4720 }
4721
Christopher Tate043dadc2009-06-02 16:11:00 -07004722 // Callback: a requested backup agent has been instantiated. This should only
4723 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004724 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07004725 synchronized(mAgentConnectLock) {
4726 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004727 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07004728 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
4729 mConnectedAgent = agent;
4730 mConnecting = false;
4731 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004732 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004733 + " claiming agent connected");
4734 }
4735 mAgentConnectLock.notifyAll();
4736 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004737 }
4738
4739 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
4740 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07004741 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004742 public void agentDisconnected(String packageName) {
4743 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07004744 synchronized(mAgentConnectLock) {
4745 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
4746 mConnectedAgent = null;
4747 mConnecting = false;
4748 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004749 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004750 + " claiming agent disconnected");
4751 }
4752 mAgentConnectLock.notifyAll();
4753 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004754 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004755
Christopher Tate1bb69062010-02-19 17:02:12 -08004756 // An application being installed will need a restore pass, then the Package Manager
4757 // will need to be told when the restore is finished.
4758 public void restoreAtInstall(String packageName, int token) {
4759 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004760 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08004761 + " attemping install-time restore");
4762 return;
4763 }
4764
4765 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004766 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08004767 + " token=" + Integer.toHexString(token));
4768
Christopher Tatef0872722010-02-25 15:22:48 -08004769 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08004770 // okay, we're going to attempt a restore of this package from this restore set.
4771 // The eventual message back into the Package Manager to run the post-install
4772 // steps for 'token' will be issued from the restore handling code.
4773
4774 // We can use a synthetic PackageInfo here because:
4775 // 1. We know it's valid, since the Package Manager supplied the name
4776 // 2. Only the packageName field will be used by the restore code
4777 PackageInfo pkg = new PackageInfo();
4778 pkg.packageName = packageName;
4779
4780 mWakelock.acquire();
4781 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4782 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07004783 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08004784 mBackupHandler.sendMessage(msg);
4785 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08004786 // Auto-restore disabled or no way to attempt a restore; just tell the Package
4787 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004788 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08004789 try {
4790 mPackageManagerBinder.finishPackageInstall(token);
4791 } catch (RemoteException e) { /* can't happen */ }
4792 }
4793 }
4794
Christopher Tate8c850b72009-06-07 19:33:20 -07004795 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08004796 public IRestoreSession beginRestoreSession(String packageName, String transport) {
4797 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
4798 + " transport=" + transport);
4799
4800 boolean needPermission = true;
4801 if (transport == null) {
4802 transport = mCurrentTransport;
4803
4804 if (packageName != null) {
4805 PackageInfo app = null;
4806 try {
4807 app = mPackageManager.getPackageInfo(packageName, 0);
4808 } catch (NameNotFoundException nnf) {
4809 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
4810 throw new IllegalArgumentException("Package " + packageName + " not found");
4811 }
4812
4813 if (app.applicationInfo.uid == Binder.getCallingUid()) {
4814 // So: using the current active transport, and the caller has asked
4815 // that its own package will be restored. In this narrow use case
4816 // we do not require the caller to hold the permission.
4817 needPermission = false;
4818 }
4819 }
4820 }
4821
4822 if (needPermission) {
4823 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4824 "beginRestoreSession");
4825 } else {
4826 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
4827 }
Christopher Tatef68eb502009-06-16 11:02:01 -07004828
4829 synchronized(this) {
4830 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004831 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07004832 return null;
4833 }
Chris Tate44ab8452010-11-16 15:10:49 -08004834 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08004835 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07004836 }
4837 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07004838 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004839
Christopher Tate73a3cb32010-12-13 18:27:26 -08004840 void clearRestoreSession(ActiveRestoreSession currentSession) {
4841 synchronized(this) {
4842 if (currentSession != mActiveRestoreSession) {
4843 Slog.e(TAG, "ending non-current restore session");
4844 } else {
4845 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
4846 mActiveRestoreSession = null;
4847 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4848 }
4849 }
4850 }
4851
Christopher Tate44a27902010-01-27 17:15:49 -08004852 // Note that a currently-active backup agent has notified us that it has
4853 // completed the given outstanding asynchronous backup/restore operation.
4854 public void opComplete(int token) {
4855 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004856 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08004857 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
4858 mCurrentOpLock.notifyAll();
4859 }
4860 }
4861
Christopher Tate9b3905c2009-06-08 15:24:01 -07004862 // ----- Restore session -----
4863
Christopher Tate80202c82010-01-25 19:37:47 -08004864 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07004865 private static final String TAG = "RestoreSession";
4866
Chris Tate44ab8452010-11-16 15:10:49 -08004867 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004868 private IBackupTransport mRestoreTransport = null;
4869 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08004870 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004871
Chris Tate44ab8452010-11-16 15:10:49 -08004872 ActiveRestoreSession(String packageName, String transport) {
4873 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07004874 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07004875 }
4876
4877 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07004878 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04004879 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004880 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004881 if (observer == null) {
4882 throw new IllegalArgumentException("Observer must not be null");
4883 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004884
Christopher Tate73a3cb32010-12-13 18:27:26 -08004885 if (mEnded) {
4886 throw new IllegalStateException("Restore session already ended");
4887 }
4888
Christopher Tate1bb69062010-02-19 17:02:12 -08004889 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07004890 try {
Christopher Tate43383042009-07-13 15:17:13 -07004891 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004892 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004893 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07004894 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07004895 // spin off the transport request to our service thread
4896 mWakelock.acquire();
4897 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
4898 new RestoreGetSetsParams(mRestoreTransport, this, observer));
4899 mBackupHandler.sendMessage(msg);
4900 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07004901 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004902 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07004903 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08004904 } finally {
4905 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07004906 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07004907 }
4908
Christopher Tate84725812010-02-04 15:52:40 -08004909 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07004910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4911 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004912
Chris Tate44ab8452010-11-16 15:10:49 -08004913 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07004914 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004915
Christopher Tate73a3cb32010-12-13 18:27:26 -08004916 if (mEnded) {
4917 throw new IllegalStateException("Restore session already ended");
4918 }
4919
Dan Egnor0084da52009-07-29 12:57:16 -07004920 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08004921 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4922 return -1;
4923 }
4924
4925 if (mPackageName != null) {
4926 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07004927 return -1;
4928 }
4929
Christopher Tate21ab6a52009-09-24 18:01:46 -07004930 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004931 for (int i = 0; i < mRestoreSets.length; i++) {
4932 if (token == mRestoreSets[i].token) {
4933 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07004934 mWakelock.acquire();
4935 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004936 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07004937 mBackupHandler.sendMessage(msg);
4938 Binder.restoreCallingIdentity(oldId);
4939 return 0;
4940 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004941 }
4942 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07004943
Joe Onorato8a9b2202010-02-26 18:56:32 -08004944 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07004945 return -1;
4946 }
4947
Christopher Tate284f1bb2011-07-07 14:31:18 -07004948 public synchronized int restoreSome(long token, IRestoreObserver observer,
4949 String[] packages) {
4950 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4951 "performRestore");
4952
4953 if (DEBUG) {
4954 StringBuilder b = new StringBuilder(128);
4955 b.append("restoreSome token=");
4956 b.append(Long.toHexString(token));
4957 b.append(" observer=");
4958 b.append(observer.toString());
4959 b.append(" packages=");
4960 if (packages == null) {
4961 b.append("null");
4962 } else {
4963 b.append('{');
4964 boolean first = true;
4965 for (String s : packages) {
4966 if (!first) {
4967 b.append(", ");
4968 } else first = false;
4969 b.append(s);
4970 }
4971 b.append('}');
4972 }
4973 Slog.d(TAG, b.toString());
4974 }
4975
4976 if (mEnded) {
4977 throw new IllegalStateException("Restore session already ended");
4978 }
4979
4980 if (mRestoreTransport == null || mRestoreSets == null) {
4981 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4982 return -1;
4983 }
4984
4985 if (mPackageName != null) {
4986 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
4987 return -1;
4988 }
4989
4990 synchronized (mQueueLock) {
4991 for (int i = 0; i < mRestoreSets.length; i++) {
4992 if (token == mRestoreSets[i].token) {
4993 long oldId = Binder.clearCallingIdentity();
4994 mWakelock.acquire();
4995 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4996 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
4997 packages, true);
4998 mBackupHandler.sendMessage(msg);
4999 Binder.restoreCallingIdentity(oldId);
5000 return 0;
5001 }
5002 }
5003 }
5004
5005 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
5006 return -1;
5007 }
5008
Christopher Tate84725812010-02-04 15:52:40 -08005009 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005010 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08005011
Christopher Tate73a3cb32010-12-13 18:27:26 -08005012 if (mEnded) {
5013 throw new IllegalStateException("Restore session already ended");
5014 }
5015
Chris Tate44ab8452010-11-16 15:10:49 -08005016 if (mPackageName != null) {
5017 if (! mPackageName.equals(packageName)) {
5018 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
5019 + " on session for package " + mPackageName);
5020 return -1;
5021 }
5022 }
5023
Christopher Tate84725812010-02-04 15:52:40 -08005024 PackageInfo app = null;
5025 try {
5026 app = mPackageManager.getPackageInfo(packageName, 0);
5027 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005028 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005029 return -1;
5030 }
5031
5032 // If the caller is not privileged and is not coming from the target
5033 // app's uid, throw a permission exception back to the caller.
5034 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
5035 Binder.getCallingPid(), Binder.getCallingUid());
5036 if ((perm == PackageManager.PERMISSION_DENIED) &&
5037 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005038 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08005039 + " or calling uid=" + Binder.getCallingUid());
5040 throw new SecurityException("No permission to restore other packages");
5041 }
5042
Christopher Tate7d411a32010-02-26 11:27:08 -08005043 // If the package has no backup agent, we obviously cannot proceed
5044 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005045 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08005046 return -1;
5047 }
5048
Christopher Tate84725812010-02-04 15:52:40 -08005049 // So far so good; we're allowed to try to restore this package. Now
5050 // check whether there is data for it in the current dataset, falling back
5051 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08005052 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08005053
5054 // If we didn't come up with a place to look -- no ancestral dataset and
5055 // the app has never been backed up from this device -- there's nothing
5056 // to do but return failure.
5057 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08005058 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08005059 return -1;
5060 }
5061
5062 // Ready to go: enqueue the restore request and claim success
5063 long oldId = Binder.clearCallingIdentity();
5064 mWakelock.acquire();
5065 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07005066 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08005067 mBackupHandler.sendMessage(msg);
5068 Binder.restoreCallingIdentity(oldId);
5069 return 0;
5070 }
5071
Christopher Tate73a3cb32010-12-13 18:27:26 -08005072 // Posted to the handler to tear down a restore session in a cleanly synchronized way
5073 class EndRestoreRunnable implements Runnable {
5074 BackupManagerService mBackupManager;
5075 ActiveRestoreSession mSession;
5076
5077 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
5078 mBackupManager = manager;
5079 mSession = session;
5080 }
5081
5082 public void run() {
5083 // clean up the session's bookkeeping
5084 synchronized (mSession) {
5085 try {
5086 if (mSession.mRestoreTransport != null) {
5087 mSession.mRestoreTransport.finishRestore();
5088 }
5089 } catch (Exception e) {
5090 Slog.e(TAG, "Error in finishRestore", e);
5091 } finally {
5092 mSession.mRestoreTransport = null;
5093 mSession.mEnded = true;
5094 }
5095 }
5096
5097 // clean up the BackupManagerService side of the bookkeeping
5098 // and cancel any pending timeout message
5099 mBackupManager.clearRestoreSession(mSession);
5100 }
5101 }
5102
Dan Egnor0084da52009-07-29 12:57:16 -07005103 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005104 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04005105
Christopher Tate73a3cb32010-12-13 18:27:26 -08005106 if (mEnded) {
5107 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07005108 }
5109
Christopher Tate73a3cb32010-12-13 18:27:26 -08005110 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07005111 }
5112 }
5113
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005114 @Override
5115 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005116 long identityToken = Binder.clearCallingIdentity();
5117 try {
5118 dumpInternal(pw);
5119 } finally {
5120 Binder.restoreCallingIdentity(identityToken);
5121 }
5122 }
5123
5124 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005125 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07005126 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07005127 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08005128 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08005129 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07005130 pw.println("Last backup pass: " + mLastBackupPass
5131 + " (now = " + System.currentTimeMillis() + ')');
5132 pw.println(" next scheduled: " + mNextBackupPass);
5133
Christopher Tate91717492009-06-26 21:07:13 -07005134 pw.println("Available transports:");
5135 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07005136 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
5137 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005138 IBackupTransport transport = getTransport(t);
5139 File dir = new File(mBaseStateDir, transport.transportDirName());
5140 pw.println(" destination: " + transport.currentDestinationString());
5141 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07005142 for (File f : dir.listFiles()) {
5143 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
5144 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08005145 } catch (Exception e) {
5146 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07005147 pw.println(" Error: " + e);
5148 }
Christopher Tate91717492009-06-26 21:07:13 -07005149 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005150
5151 pw.println("Pending init: " + mPendingInits.size());
5152 for (String s : mPendingInits) {
5153 pw.println(" " + s);
5154 }
5155
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005156 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07005157 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005158 for (int i=0; i<N; i++) {
5159 int uid = mBackupParticipants.keyAt(i);
5160 pw.print(" uid: ");
5161 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005162 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
5163 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07005164 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005165 }
5166 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005167
Christopher Tateb49ceb32010-02-08 16:22:24 -08005168 pw.println("Ancestral packages: "
5169 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07005170 if (mAncestralPackages != null) {
5171 for (String pkg : mAncestralPackages) {
5172 pw.println(" " + pkg);
5173 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08005174 }
5175
Christopher Tate73e02522009-07-15 14:18:26 -07005176 pw.println("Ever backed up: " + mEverStoredApps.size());
5177 for (String pkg : mEverStoredApps) {
5178 pw.println(" " + pkg);
5179 }
Christopher Tate55f931a2009-09-29 17:17:34 -07005180
5181 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07005182 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07005183 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07005184 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07005185 }
5186 }
Christopher Tate487529a2009-04-29 14:03:25 -07005187}