blob: e9e66cb9d164541d544a7c034043287089f927c2 [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 Tate7926a692011-07-11 11:31:57 -070079import java.io.DataInputStream;
Christopher Tatecde87f42009-06-12 12:55:53 -070080import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070081import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070082import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070083import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080084import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070085import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070086import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070087import java.io.InputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070088import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070089import java.io.RandomAccessFile;
Christopher Tate7bdb0962011-07-13 19:30:21 -070090import java.io.UnsupportedEncodingException;
Christopher Tate75a99702011-05-18 16:28:19 -070091import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -040092import java.util.ArrayList;
Christopher Tate7bdb0962011-07-13 19:30:21 -070093import java.util.Arrays;
Christopher Tate75a99702011-05-18 16:28:19 -070094import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -040095import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070096import java.util.HashSet;
97import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070098import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070099import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800100import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -0700101import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate7926a692011-07-11 11:31:57 -0700102import java.util.zip.Deflater;
103import java.util.zip.DeflaterOutputStream;
104import java.util.zip.Inflater;
105import java.util.zip.InflaterInputStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700106
107class BackupManagerService extends IBackupManager.Stub {
108 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700109 private static final boolean DEBUG = true;
110
111 // Name and current contents version of the full-backup manifest file
112 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
113 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tate7bdb0962011-07-13 19:30:21 -0700114 static final String BACKUP_FILE_HEADER_MAGIC = "ANDROID BACKUP\n";
115 static final int BACKUP_FILE_VERSION = 1;
Christopher Tateaa088442009-06-16 18:25:46 -0700116
Christopher Tate49401dd2009-07-01 12:34:29 -0700117 // How often we perform a backup pass. Privileged external callers can
118 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700119 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700120
Dan Egnorc1c49c02009-10-30 17:35:39 -0700121 // Random variation in backup scheduling time to avoid server load spikes
122 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
123
Christopher Tate8031a3d2009-07-06 16:36:05 -0700124 // The amount of time between the initial provisioning of the device and
125 // the first backup pass.
126 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
127
Christopher Tate45281862010-03-05 15:46:30 -0800128 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
129 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
130 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700131 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700132 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700133 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700134 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700135 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700136 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
137 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800138 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700139 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
140 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700141
142 // Timeout interval for deciding that a bind or clear-data has taken too long
143 static final long TIMEOUT_INTERVAL = 10 * 1000;
144
Christopher Tate44a27902010-01-27 17:15:49 -0800145 // Timeout intervals for agent backup & restore operations
146 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700147 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700148 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800149 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
150
Christopher Tate4a627c72011-04-01 14:43:32 -0700151 // User confirmation timeout for a full backup/restore operation
152 static final long TIMEOUT_FULL_CONFIRMATION = 30 * 1000;
153
Christopher Tate487529a2009-04-29 14:03:25 -0700154 private Context mContext;
155 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800156 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700157 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700158 private PowerManager mPowerManager;
159 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800160 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700161
Christopher Tate73e02522009-07-15 14:18:26 -0700162 boolean mEnabled; // access to this is synchronized on 'this'
163 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800164 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700165 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800166 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
167 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700168 PendingIntent mRunBackupIntent, mRunInitIntent;
169 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700170 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700171 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700172 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700173 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700174 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700175 public ApplicationInfo appInfo;
Christopher Tateaa088442009-06-16 18:25:46 -0700176
Christopher Tate4a627c72011-04-01 14:43:32 -0700177 BackupRequest(ApplicationInfo app) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700178 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700179 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700180
181 public String toString() {
Christopher Tate4a627c72011-04-01 14:43:32 -0700182 return "BackupRequest{app=" + appInfo + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700183 }
Christopher Tate46758122009-05-06 11:22:00 -0700184 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800185 // Backups that we haven't started yet. Keys are package names.
186 HashMap<String,BackupRequest> mPendingBackups
187 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700188
189 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700190 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700191
192 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700193 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700194
Christopher Tate043dadc2009-06-02 16:11:00 -0700195 // The thread performing the sequence of queued backups binds to each app's agent
196 // in succession. Bind notifications are asynchronously delivered through the
197 // Activity Manager; use this lock object to signal when a requested binding has
198 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700199 final Object mAgentConnectLock = new Object();
200 IBackupAgent mConnectedAgent;
201 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700202 volatile long mLastBackupPass;
203 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700204
Christopher Tate55f931a2009-09-29 17:17:34 -0700205 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700206 final Object mClearDataLock = new Object();
207 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700208
Christopher Tate91717492009-06-26 21:07:13 -0700209 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700210 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700211 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700212 String mCurrentTransport;
213 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800214 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700215
Christopher Tate2d449afe2010-03-29 19:14:24 -0700216 class RestoreGetSetsParams {
217 public IBackupTransport transport;
218 public ActiveRestoreSession session;
219 public IRestoreObserver observer;
220
221 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
222 IRestoreObserver _observer) {
223 transport = _transport;
224 session = _session;
225 observer = _observer;
226 }
227 }
228
Christopher Tate73e02522009-07-15 14:18:26 -0700229 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700230 public IBackupTransport transport;
231 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700232 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800233 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800234 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700235 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700236 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800237
238 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700239 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800240 transport = _transport;
241 observer = _obs;
242 token = _token;
243 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800244 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700245 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700246 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800247 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700248
Chris Tate249345b2010-10-29 12:57:04 -0700249 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
250 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700251 transport = _transport;
252 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700253 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800254 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800255 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700256 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700257 filterSet = null;
258 }
259
260 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
261 String[] _filterSet, boolean _needFullBackup) {
262 transport = _transport;
263 observer = _obs;
264 token = _token;
265 pkgInfo = null;
266 pmToken = 0;
267 needFullBackup = _needFullBackup;
268 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700269 }
270 }
271
Christopher Tate73e02522009-07-15 14:18:26 -0700272 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700273 public IBackupTransport transport;
274 public PackageInfo packageInfo;
275
276 ClearParams(IBackupTransport _transport, PackageInfo _info) {
277 transport = _transport;
278 packageInfo = _info;
279 }
280 }
281
Christopher Tate4a627c72011-04-01 14:43:32 -0700282 class FullParams {
283 public ParcelFileDescriptor fd;
284 public final AtomicBoolean latch;
285 public IFullBackupRestoreObserver observer;
286
287 FullParams() {
288 latch = new AtomicBoolean(false);
289 }
290 }
291
292 class FullBackupParams extends FullParams {
293 public boolean includeApks;
294 public boolean includeShared;
295 public boolean allApps;
296 public String[] packages;
297
298 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
299 boolean doAllApps, String[] pkgList) {
300 fd = output;
301 includeApks = saveApks;
302 includeShared = saveShared;
303 allApps = doAllApps;
304 packages = pkgList;
305 }
306 }
307
308 class FullRestoreParams extends FullParams {
309 FullRestoreParams(ParcelFileDescriptor input) {
310 fd = input;
311 }
312 }
313
Christopher Tate44a27902010-01-27 17:15:49 -0800314 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
315 // token is the index of the entry in the pending-operations list.
316 static final int OP_PENDING = 0;
317 static final int OP_ACKNOWLEDGED = 1;
318 static final int OP_TIMEOUT = -1;
319
320 final SparseIntArray mCurrentOperations = new SparseIntArray();
321 final Object mCurrentOpLock = new Object();
322 final Random mTokenGenerator = new Random();
323
Christopher Tate4a627c72011-04-01 14:43:32 -0700324 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
325
Christopher Tate5cb400b2009-06-25 16:03:14 -0700326 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700327 File mBaseStateDir;
328 File mDataDir;
329 File mJournalDir;
330 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700331
Christopher Tate84725812010-02-04 15:52:40 -0800332 // Keep a log of all the apps we've ever backed up, and what the
333 // dataset tokens are for both the current backup dataset and
334 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700335 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700336 HashSet<String> mEverStoredApps = new HashSet<String>();
337
Christopher Tateb49ceb32010-02-08 16:22:24 -0800338 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800339 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800340 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800341 long mAncestralToken = 0;
342 long mCurrentToken = 0;
343
Christopher Tate4cc86e12009-09-21 19:36:51 -0700344 // Persistently track the need to do a full init
345 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
346 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700347
Christopher Tate4a627c72011-04-01 14:43:32 -0700348 // Utility: build a new random integer token
349 int generateToken() {
350 int token;
351 do {
352 synchronized (mTokenGenerator) {
353 token = mTokenGenerator.nextInt();
354 }
355 } while (token < 0);
356 return token;
357 }
358
Christopher Tate44a27902010-01-27 17:15:49 -0800359 // ----- Asynchronous backup/restore handler thread -----
360
361 private class BackupHandler extends Handler {
362 public BackupHandler(Looper looper) {
363 super(looper);
364 }
365
366 public void handleMessage(Message msg) {
367
368 switch (msg.what) {
369 case MSG_RUN_BACKUP:
370 {
371 mLastBackupPass = System.currentTimeMillis();
372 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
373
374 IBackupTransport transport = getTransport(mCurrentTransport);
375 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800376 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800377 mWakelock.release();
378 break;
379 }
380
381 // snapshot the pending-backup set and work on that
382 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800383 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800384 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800385 // Do we have any work to do? Construct the work queue
386 // then release the synchronization lock to actually run
387 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800388 if (mPendingBackups.size() > 0) {
389 for (BackupRequest b: mPendingBackups.values()) {
390 queue.add(b);
391 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800392 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800393 mPendingBackups.clear();
394
395 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800396 mJournal = null;
397
Christopher Tate44a27902010-01-27 17:15:49 -0800398 }
399 }
Christopher Tatec61da312010-02-05 10:41:27 -0800400
401 if (queue.size() > 0) {
402 // At this point, we have started a new journal file, and the old
403 // file identity is being passed to the backup processing thread.
404 // When it completes successfully, that old journal file will be
405 // deleted. If we crash prior to that, the old journal is parsed
406 // at next boot and the journaled requests fulfilled.
407 (new PerformBackupTask(transport, queue, oldJournal)).run();
408 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800409 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800410 mWakelock.release();
411 }
Christopher Tate44a27902010-01-27 17:15:49 -0800412 break;
413 }
414
415 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700416 {
417 FullBackupParams params = (FullBackupParams)msg.obj;
418 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
419 params.includeShared, params.allApps, params.packages,
420 params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800421 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700422 }
Christopher Tate44a27902010-01-27 17:15:49 -0800423
424 case MSG_RUN_RESTORE:
425 {
426 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800427 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800428 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700429 params.token, params.pkgInfo, params.pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -0700430 params.needFullBackup, params.filterSet)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800431 break;
432 }
433
Christopher Tate75a99702011-05-18 16:28:19 -0700434 case MSG_RUN_FULL_RESTORE:
435 {
436 FullRestoreParams params = (FullRestoreParams)msg.obj;
437 (new PerformFullRestoreTask(params.fd, params.observer, params.latch)).run();
438 break;
439 }
440
Christopher Tate44a27902010-01-27 17:15:49 -0800441 case MSG_RUN_CLEAR:
442 {
443 ClearParams params = (ClearParams)msg.obj;
444 (new PerformClearTask(params.transport, params.packageInfo)).run();
445 break;
446 }
447
448 case MSG_RUN_INITIALIZE:
449 {
450 HashSet<String> queue;
451
452 // Snapshot the pending-init queue and work on that
453 synchronized (mQueueLock) {
454 queue = new HashSet<String>(mPendingInits);
455 mPendingInits.clear();
456 }
457
458 (new PerformInitializeTask(queue)).run();
459 break;
460 }
461
Christopher Tate2d449afe2010-03-29 19:14:24 -0700462 case MSG_RUN_GET_RESTORE_SETS:
463 {
464 // Like other async operations, this is entered with the wakelock held
465 RestoreSet[] sets = null;
466 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
467 try {
468 sets = params.transport.getAvailableRestoreSets();
469 // cache the result in the active session
470 synchronized (params.session) {
471 params.session.mRestoreSets = sets;
472 }
473 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
474 } catch (Exception e) {
475 Slog.e(TAG, "Error from transport getting set list");
476 } finally {
477 if (params.observer != null) {
478 try {
479 params.observer.restoreSetsAvailable(sets);
480 } catch (RemoteException re) {
481 Slog.e(TAG, "Unable to report listing to observer");
482 } catch (Exception e) {
483 Slog.e(TAG, "Restore observer threw", e);
484 }
485 }
486
Christopher Tate2a935092011-03-03 17:30:32 -0800487 // Done: reset the session timeout clock
488 removeMessages(MSG_RESTORE_TIMEOUT);
489 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
490
Christopher Tate2d449afe2010-03-29 19:14:24 -0700491 mWakelock.release();
492 }
493 break;
494 }
495
Christopher Tate44a27902010-01-27 17:15:49 -0800496 case MSG_TIMEOUT:
497 {
498 synchronized (mCurrentOpLock) {
499 final int token = msg.arg1;
500 int state = mCurrentOperations.get(token, OP_TIMEOUT);
501 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800502 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800503 mCurrentOperations.put(token, OP_TIMEOUT);
504 }
505 mCurrentOpLock.notifyAll();
506 }
507 break;
508 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800509
510 case MSG_RESTORE_TIMEOUT:
511 {
512 synchronized (BackupManagerService.this) {
513 if (mActiveRestoreSession != null) {
514 // Client app left the restore session dangling. We know that it
515 // can't be in the middle of an actual restore operation because
516 // those are executed serially on this same handler thread. Clean
517 // up now.
518 Slog.w(TAG, "Restore session timed out; aborting");
519 post(mActiveRestoreSession.new EndRestoreRunnable(
520 BackupManagerService.this, mActiveRestoreSession));
521 }
522 }
523 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700524
525 case MSG_FULL_CONFIRMATION_TIMEOUT:
526 {
527 synchronized (mFullConfirmations) {
528 FullParams params = mFullConfirmations.get(msg.arg1);
529 if (params != null) {
530 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
531
532 // Release the waiter; timeout == completion
533 signalFullBackupRestoreCompletion(params);
534
535 // Remove the token from the set
536 mFullConfirmations.delete(msg.arg1);
537
538 // Report a timeout to the observer, if any
539 if (params.observer != null) {
540 try {
541 params.observer.onTimeout();
542 } catch (RemoteException e) {
543 /* don't care if the app has gone away */
544 }
545 }
546 } else {
547 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
548 }
549 }
550 break;
551 }
Christopher Tate44a27902010-01-27 17:15:49 -0800552 }
553 }
554 }
555
556 // ----- Main service implementation -----
557
Christopher Tate487529a2009-04-29 14:03:25 -0700558 public BackupManagerService(Context context) {
559 mContext = context;
560 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700561 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700562 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700563
Christopher Tateb6787f22009-07-02 17:40:45 -0700564 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
565 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
566
Christopher Tate44a27902010-01-27 17:15:49 -0800567 mBackupManagerBinder = asInterface(asBinder());
568
569 // spin up the backup/restore handler thread
570 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
571 mHandlerThread.start();
572 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
573
Christopher Tate22b87872009-05-04 16:41:53 -0700574 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700575 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700576 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700577 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700578 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800579 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800580 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800581 // If Encrypted file systems is enabled or disabled, this call will return the
582 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600583 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800584 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700585 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700586
Christopher Tate4cc86e12009-09-21 19:36:51 -0700587 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700588 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700589 IntentFilter filter = new IntentFilter();
590 filter.addAction(RUN_BACKUP_ACTION);
591 context.registerReceiver(mRunBackupReceiver, filter,
592 android.Manifest.permission.BACKUP, null);
593
594 mRunInitReceiver = new RunInitializeReceiver();
595 filter = new IntentFilter();
596 filter.addAction(RUN_INITIALIZE_ACTION);
597 context.registerReceiver(mRunInitReceiver, filter,
598 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700599
600 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700601 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
602 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
603
Christopher Tate4cc86e12009-09-21 19:36:51 -0700604 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
605 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
606 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
607
Christopher Tatecde87f42009-06-12 12:55:53 -0700608 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700609 mJournalDir = new File(mBaseStateDir, "pending");
610 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700611 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700612
Christopher Tate73e02522009-07-15 14:18:26 -0700613 // Set up the various sorts of package tracking we do
614 initPackageTracking();
615
Christopher Tateabce4e82009-06-18 18:35:32 -0700616 // Build our mapping of uid to backup client services. This implicitly
617 // schedules a backup pass on the Package Manager metadata the first
618 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700619 synchronized (mBackupParticipants) {
620 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700621 }
622
Dan Egnor87a02bc2009-06-17 02:30:10 -0700623 // Set up our transport options and initialize the default transport
624 // TODO: Have transports register themselves somehow?
625 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700626 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700627 ComponentName localName = new ComponentName(context, LocalTransport.class);
628 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700629
Christopher Tate91717492009-06-26 21:07:13 -0700630 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700631 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
632 Settings.Secure.BACKUP_TRANSPORT);
633 if ("".equals(mCurrentTransport)) {
634 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700635 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800636 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700637
638 // Attach to the Google backup transport. When this comes up, it will set
639 // itself as the current transport because we explicitly reset mCurrentTransport
640 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700641 ComponentName transportComponent = new ComponentName("com.google.android.backup",
642 "com.google.android.backup.BackupTransportService");
643 try {
644 // If there's something out there that is supposed to be the Google
645 // backup transport, make sure it's legitimately part of the OS build
646 // and not an app lying about its package name.
647 ApplicationInfo info = mPackageManager.getApplicationInfo(
648 transportComponent.getPackageName(), 0);
649 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
650 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
651 Intent intent = new Intent().setComponent(transportComponent);
652 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
653 } else {
654 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
655 }
656 } catch (PackageManager.NameNotFoundException nnf) {
657 // No such package? No binding.
658 if (DEBUG) Slog.v(TAG, "Google transport not present");
659 }
Christopher Tateaa088442009-06-16 18:25:46 -0700660
Christopher Tatecde87f42009-06-12 12:55:53 -0700661 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700662 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700663 parseLeftoverJournals();
664
Christopher Tateb6787f22009-07-02 17:40:45 -0700665 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700666 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700667
668 // Start the backup passes going
669 setBackupEnabled(areEnabled);
670 }
671
672 private class RunBackupReceiver extends BroadcastReceiver {
673 public void onReceive(Context context, Intent intent) {
674 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700675 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700676 if (mPendingInits.size() > 0) {
677 // If there are pending init operations, we process those
678 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800679 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700680 try {
681 mAlarmManager.cancel(mRunInitIntent);
682 mRunInitIntent.send();
683 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800684 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700685 // can't really do more than bail here
686 }
687 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800688 // Don't run backups now if we're disabled or not yet
689 // fully set up.
690 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800691 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700692
693 // Acquire the wakelock and pass it to the backup thread. it will
694 // be released once backup concludes.
695 mWakelock.acquire();
696
697 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
698 mBackupHandler.sendMessage(msg);
699 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800700 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700701 }
702 }
703 }
704 }
705 }
706 }
707
708 private class RunInitializeReceiver extends BroadcastReceiver {
709 public void onReceive(Context context, Intent intent) {
710 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
711 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800712 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700713
714 // Acquire the wakelock and pass it to the init thread. it will
715 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700716 mWakelock.acquire();
717
Christopher Tate4cc86e12009-09-21 19:36:51 -0700718 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700719 mBackupHandler.sendMessage(msg);
720 }
721 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700722 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700723 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700724
Christopher Tate73e02522009-07-15 14:18:26 -0700725 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800726 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700727
Christopher Tate84725812010-02-04 15:52:40 -0800728 // Remember our ancestral dataset
729 mTokenFile = new File(mBaseStateDir, "ancestral");
730 try {
731 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800732 int version = tf.readInt();
733 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
734 mAncestralToken = tf.readLong();
735 mCurrentToken = tf.readLong();
736
737 int numPackages = tf.readInt();
738 if (numPackages >= 0) {
739 mAncestralPackages = new HashSet<String>();
740 for (int i = 0; i < numPackages; i++) {
741 String pkgName = tf.readUTF();
742 mAncestralPackages.add(pkgName);
743 }
744 }
745 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800746 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800747 } catch (FileNotFoundException fnf) {
748 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800749 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800750 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800751 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800752 }
753
Christopher Tatee97e8072009-07-15 16:45:50 -0700754 // Keep a log of what apps we've ever backed up. Because we might have
755 // rebooted in the middle of an operation that was removing something from
756 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700757 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700758 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700759
Christopher Tatee97e8072009-07-15 16:45:50 -0700760 // If we were in the middle of removing something from the ever-backed-up
761 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700762 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700763 if (tempProcessedFile.exists()) {
764 tempProcessedFile.delete();
765 }
766
Dan Egnor852f8e42009-09-30 11:20:45 -0700767 // If there are previous contents, parse them out then start a new
768 // file to continue the recordkeeping.
769 if (mEverStored.exists()) {
770 RandomAccessFile temp = null;
771 RandomAccessFile in = null;
772
773 try {
774 temp = new RandomAccessFile(tempProcessedFile, "rws");
775 in = new RandomAccessFile(mEverStored, "r");
776
777 while (true) {
778 PackageInfo info;
779 String pkg = in.readUTF();
780 try {
781 info = mPackageManager.getPackageInfo(pkg, 0);
782 mEverStoredApps.add(pkg);
783 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800784 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700785 } catch (NameNotFoundException e) {
786 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800787 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700788 }
789 }
790 } catch (EOFException e) {
791 // Once we've rewritten the backup history log, atomically replace the
792 // old one with the new one then reopen the file for continuing use.
793 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800794 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700795 }
796 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800797 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700798 } finally {
799 try { if (temp != null) temp.close(); } catch (IOException e) {}
800 try { if (in != null) in.close(); } catch (IOException e) {}
801 }
802 }
803
Christopher Tate73e02522009-07-15 14:18:26 -0700804 // Register for broadcasts about package install, etc., so we can
805 // update the provider list.
806 IntentFilter filter = new IntentFilter();
807 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
808 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
809 filter.addDataScheme("package");
810 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800811 // Register for events related to sdcard installation.
812 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800813 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
814 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800815 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700816 }
817
Christopher Tatecde87f42009-06-12 12:55:53 -0700818 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700819 for (File f : mJournalDir.listFiles()) {
820 if (mJournal == null || f.compareTo(mJournal) != 0) {
821 // This isn't the current journal, so it must be a leftover. Read
822 // out the package names mentioned there and schedule them for
823 // backup.
824 RandomAccessFile in = null;
825 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400826 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700827 in = new RandomAccessFile(f, "r");
828 while (true) {
829 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400830 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700831 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700832 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700833 } catch (EOFException e) {
834 // no more data; we're done
835 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800836 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700837 } finally {
838 // close/delete the file
839 try { if (in != null) in.close(); } catch (IOException e) {}
840 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700841 }
842 }
843 }
844 }
845
Christopher Tate4cc86e12009-09-21 19:36:51 -0700846 // Maintain persistent state around whether need to do an initialize operation.
847 // Must be called with the queue lock held.
848 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800849 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700850 + " on transport " + transportName);
851 try {
852 IBackupTransport transport = getTransport(transportName);
853 String transportDirName = transport.transportDirName();
854 File stateDir = new File(mBaseStateDir, transportDirName);
855 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
856
857 if (isPending) {
858 // We need an init before we can proceed with sending backup data.
859 // Record that with an entry in our set of pending inits, as well as
860 // journaling it via creation of a sentinel file.
861 mPendingInits.add(transportName);
862 try {
863 (new FileOutputStream(initPendingFile)).close();
864 } catch (IOException ioe) {
865 // Something is badly wrong with our permissions; just try to move on
866 }
867 } else {
868 // No more initialization needed; wipe the journal and reset our state.
869 initPendingFile.delete();
870 mPendingInits.remove(transportName);
871 }
872 } catch (RemoteException e) {
873 // can't happen; the transport is local
874 }
875 }
876
Christopher Tated55e18a2009-09-21 10:12:59 -0700877 // Reset all of our bookkeeping, in response to having been told that
878 // the backend data has been wiped [due to idle expiry, for example],
879 // so we must re-upload all saved settings.
880 void resetBackupState(File stateFileDir) {
881 synchronized (mQueueLock) {
882 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700883 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700884 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700885
Christopher Tate84725812010-02-04 15:52:40 -0800886 mCurrentToken = 0;
887 writeRestoreTokens();
888
Christopher Tated55e18a2009-09-21 10:12:59 -0700889 // Remove all the state files
890 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700891 // ... but don't touch the needs-init sentinel
892 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
893 sf.delete();
894 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700895 }
Christopher Tate45597642011-04-04 16:59:21 -0700896 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700897
Christopher Tate45597642011-04-04 16:59:21 -0700898 // Enqueue a new backup of every participant
899 int N = mBackupParticipants.size();
900 for (int i=0; i<N; i++) {
901 int uid = mBackupParticipants.keyAt(i);
902 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
903 for (ApplicationInfo app: participants) {
904 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700905 }
906 }
907 }
908
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800909 // Add a transport to our set of available backends. If 'transport' is null, this
910 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700911 private void registerTransport(String name, IBackupTransport transport) {
912 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800913 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800914 if (transport != null) {
915 mTransports.put(name, transport);
916 } else {
917 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800918 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800919 mCurrentTransport = null;
920 }
921 // Nothing further to do in the unregistration case
922 return;
923 }
Christopher Tate91717492009-06-26 21:07:13 -0700924 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700925
926 // If the init sentinel file exists, we need to be sure to perform the init
927 // as soon as practical. We also create the state directory at registration
928 // time to ensure it's present from the outset.
929 try {
930 String transportName = transport.transportDirName();
931 File stateDir = new File(mBaseStateDir, transportName);
932 stateDir.mkdirs();
933
934 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
935 if (initSentinel.exists()) {
936 synchronized (mQueueLock) {
937 mPendingInits.add(transportName);
938
939 // TODO: pick a better starting time than now + 1 minute
940 long delay = 1000 * 60; // one minute, in milliseconds
941 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
942 System.currentTimeMillis() + delay, mRunInitIntent);
943 }
944 }
945 } catch (RemoteException e) {
946 // can't happen, the transport is local
947 }
Christopher Tate91717492009-06-26 21:07:13 -0700948 }
949
Christopher Tate3799bc22009-05-06 16:13:56 -0700950 // ----- Track installation/removal of packages -----
951 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
952 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800953 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700954
Christopher Tate3799bc22009-05-06 16:13:56 -0700955 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800956 boolean replacing = false;
957 boolean added = false;
958 Bundle extras = intent.getExtras();
959 String pkgList[] = null;
960 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
961 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
962 Uri uri = intent.getData();
963 if (uri == null) {
964 return;
965 }
966 String pkgName = uri.getSchemeSpecificPart();
967 if (pkgName != null) {
968 pkgList = new String[] { pkgName };
969 }
970 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
971 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800972 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800973 added = true;
974 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800975 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800976 added = false;
977 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
978 }
979 if (pkgList == null || pkgList.length == 0) {
980 return;
981 }
982 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700983 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800984 for (String pkgName : pkgList) {
985 if (replacing) {
986 // The package was just upgraded
987 updatePackageParticipantsLocked(pkgName);
988 } else {
989 // The package was just added
990 addPackageParticipantsLocked(pkgName);
991 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700992 }
993 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800994 } else {
995 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700996 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
997 } else {
998 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800999 for (String pkgName : pkgList) {
1000 removePackageParticipantsLocked(pkgName);
1001 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001002 }
1003 }
1004 }
1005 }
1006 };
1007
Dan Egnor87a02bc2009-06-17 02:30:10 -07001008 // ----- Track connection to GoogleBackupTransport service -----
1009 ServiceConnection mGoogleConnection = new ServiceConnection() {
1010 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001011 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001012 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001013 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001014 }
1015
1016 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001017 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001018 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001019 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001020 }
1021 };
1022
Christopher Tate181fafa2009-05-14 11:12:14 -07001023 // Add the backup agents in the given package to our set of known backup participants.
1024 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001025 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001026 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001027 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001028 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001029 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001030 }
1031
Christopher Tate181fafa2009-05-14 11:12:14 -07001032 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001033 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001034 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001035 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001036 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001037 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001038 + " uid=" + p.applicationInfo.uid
1039 + " killAfterRestore="
1040 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001041 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001042 }
1043 }
1044
Dan Egnorefe52642009-06-24 00:16:33 -07001045 for (PackageInfo pkg : targetPkgs) {
1046 if (packageName == null || pkg.packageName.equals(packageName)) {
1047 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001048 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001049 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001050 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001051 mBackupParticipants.put(uid, set);
1052 }
Dan Egnorefe52642009-06-24 00:16:33 -07001053 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001054
1055 // If we've never seen this app before, schedule a backup for it
1056 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001057 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001058 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001059 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001060 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001061 }
Christopher Tate487529a2009-04-29 14:03:25 -07001062 }
1063 }
1064
Christopher Tate6785dd82009-06-18 15:58:25 -07001065 // Remove the given package's entry from our known active set. If
1066 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001067 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001068 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001069 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001070 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001071 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001072 } else {
1073 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001074 List<PackageInfo> knownPackages = allAgentPackages();
1075 for (PackageInfo pkg : knownPackages) {
1076 allApps.add(pkg.packageName);
1077 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001078 }
1079 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001080 }
1081
Joe Onorato8ad02812009-05-13 01:41:44 -04001082 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001083 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001084 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001085 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001086 + ") removing " + allPackageNames.size() + " entries");
1087 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001088 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001089 }
1090 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001091 for (String pkg : allPackageNames) {
1092 if (packageName == null || pkg.equals(packageName)) {
1093 int uid = -1;
1094 try {
1095 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1096 uid = info.applicationInfo.uid;
1097 } catch (NameNotFoundException e) {
1098 // we don't know this package name, so just skip it for now
1099 continue;
1100 }
1101
Christopher Tate181fafa2009-05-14 11:12:14 -07001102 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001103 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001104 // Find the existing entry with the same package name, and remove it.
1105 // We can't just remove(app) because the instances are different.
1106 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001107 if (entry.packageName.equals(pkg)) {
1108 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001109 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001110 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001111 break;
1112 }
1113 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001114 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001115 mBackupParticipants.delete(uid);
1116 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001117 }
1118 }
1119 }
1120 }
1121
Christopher Tate181fafa2009-05-14 11:12:14 -07001122 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001123 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001124 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001125 int flags = PackageManager.GET_SIGNATURES;
1126 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1127 int N = packages.size();
1128 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001129 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001130 try {
1131 ApplicationInfo app = pkg.applicationInfo;
1132 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001133 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001134 packages.remove(a);
1135 }
1136 else {
1137 // we will need the shared library path, so look that up and store it here
1138 app = mPackageManager.getApplicationInfo(pkg.packageName,
1139 PackageManager.GET_SHARED_LIBRARY_FILES);
1140 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1141 }
1142 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001143 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001144 }
1145 }
Dan Egnorefe52642009-06-24 00:16:33 -07001146 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001147 }
Christopher Tateaa088442009-06-16 18:25:46 -07001148
Christopher Tate3799bc22009-05-06 16:13:56 -07001149 // Reset the given package's known backup participants. Unlike add/remove, the update
1150 // action cannot be passed a null package name.
1151 void updatePackageParticipantsLocked(String packageName) {
1152 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001153 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001154 return;
1155 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001156 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001157
1158 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001159 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001160 List<String> allAppNames = new ArrayList<String>();
1161 for (PackageInfo pkg : allApps) {
1162 allAppNames.add(pkg.packageName);
1163 }
1164 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001165 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001166 }
1167
Christopher Tate84725812010-02-04 15:52:40 -08001168 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001169 // backed up at least once
1170 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001171 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1172
1173 synchronized (mEverStoredApps) {
1174 if (!mEverStoredApps.add(packageName)) return;
1175
1176 RandomAccessFile out = null;
1177 try {
1178 out = new RandomAccessFile(mEverStored, "rws");
1179 out.seek(out.length());
1180 out.writeUTF(packageName);
1181 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001182 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001183 } finally {
1184 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001185 }
1186 }
1187 }
1188
Christopher Tatee97e8072009-07-15 16:45:50 -07001189 // Remove our awareness of having ever backed up the given package
1190 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001191 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001192
Dan Egnor852f8e42009-09-30 11:20:45 -07001193 synchronized (mEverStoredApps) {
1194 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1195 // we'll recognize on initialization time that the package no longer
1196 // exists and fix it up then.
1197 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1198 RandomAccessFile known = null;
1199 try {
1200 known = new RandomAccessFile(tempKnownFile, "rws");
1201 mEverStoredApps.remove(packageName);
1202 for (String s : mEverStoredApps) {
1203 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001204 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001205 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001206 known.close();
1207 known = null;
1208 if (!tempKnownFile.renameTo(mEverStored)) {
1209 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1210 }
1211 } catch (IOException e) {
1212 // Bad: we couldn't create the new copy. For safety's sake we
1213 // abandon the whole process and remove all what's-backed-up
1214 // state entirely, meaning we'll force a backup pass for every
1215 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001216 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001217 mEverStoredApps.clear();
1218 tempKnownFile.delete();
1219 mEverStored.delete();
1220 } finally {
1221 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001222 }
1223 }
1224 }
1225
Christopher Tateb49ceb32010-02-08 16:22:24 -08001226 // Persistently record the current and ancestral backup tokens as well
1227 // as the set of packages with data [supposedly] available in the
1228 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001229 void writeRestoreTokens() {
1230 try {
1231 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001232
1233 // First, the version number of this record, for futureproofing
1234 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1235
1236 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001237 af.writeLong(mAncestralToken);
1238 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001239
1240 // Now write the set of ancestral packages
1241 if (mAncestralPackages == null) {
1242 af.writeInt(-1);
1243 } else {
1244 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001245 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001246 for (String pkgName : mAncestralPackages) {
1247 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001248 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001249 }
1250 }
Christopher Tate84725812010-02-04 15:52:40 -08001251 af.close();
1252 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001253 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001254 }
1255 }
1256
Dan Egnor87a02bc2009-06-17 02:30:10 -07001257 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001258 private IBackupTransport getTransport(String transportName) {
1259 synchronized (mTransports) {
1260 IBackupTransport transport = mTransports.get(transportName);
1261 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001262 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001263 }
1264 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001265 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001266 }
1267
Christopher Tatedf01dea2009-06-09 20:45:02 -07001268 // fire off a backup agent, blocking until it attaches or times out
1269 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1270 IBackupAgent agent = null;
1271 synchronized(mAgentConnectLock) {
1272 mConnecting = true;
1273 mConnectedAgent = null;
1274 try {
1275 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001276 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001277
1278 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001279 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001280 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1281 while (mConnecting && mConnectedAgent == null
1282 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001283 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001284 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001285 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001286 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001287 return null;
1288 }
1289 }
1290
1291 // if we timed out with no connect, abort and move on
1292 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001293 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001294 return null;
1295 }
1296 agent = mConnectedAgent;
1297 }
1298 } catch (RemoteException e) {
1299 // can't happen
1300 }
1301 }
1302 return agent;
1303 }
1304
Christopher Tatec7b31e32009-06-10 15:49:30 -07001305 // clear an application's data, blocking until the operation completes or times out
1306 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001307 // Don't wipe packages marked allowClearUserData=false
1308 try {
1309 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1310 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001311 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001312 + packageName);
1313 return;
1314 }
1315 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001316 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001317 return;
1318 }
1319
Christopher Tatec7b31e32009-06-10 15:49:30 -07001320 ClearDataObserver observer = new ClearDataObserver();
1321
1322 synchronized(mClearDataLock) {
1323 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001324 try {
1325 mActivityManager.clearApplicationUserData(packageName, observer);
1326 } catch (RemoteException e) {
1327 // can't happen because the activity manager is in this process
1328 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001329
1330 // only wait 10 seconds for the clear data to happen
1331 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1332 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1333 try {
1334 mClearDataLock.wait(5000);
1335 } catch (InterruptedException e) {
1336 // won't happen, but still.
1337 mClearingData = false;
1338 }
1339 }
1340 }
1341 }
1342
1343 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001344 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001345 synchronized(mClearDataLock) {
1346 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001347 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001348 }
1349 }
1350 }
1351
Christopher Tate1bb69062010-02-19 17:02:12 -08001352 // Get the restore-set token for the best-available restore set for this package:
1353 // the active set if possible, else the ancestral one. Returns zero if none available.
1354 long getAvailableRestoreToken(String packageName) {
1355 long token = mAncestralToken;
1356 synchronized (mQueueLock) {
1357 if (mEverStoredApps.contains(packageName)) {
1358 token = mCurrentToken;
1359 }
1360 }
1361 return token;
1362 }
1363
Christopher Tate44a27902010-01-27 17:15:49 -08001364 // -----
1365 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1366 boolean waitUntilOperationComplete(int token) {
1367 int finalState = OP_PENDING;
1368 synchronized (mCurrentOpLock) {
1369 try {
1370 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1371 try {
1372 mCurrentOpLock.wait();
1373 } catch (InterruptedException e) {}
1374 }
1375 } catch (IndexOutOfBoundsException e) {
1376 // the operation has been mysteriously cleared from our
1377 // bookkeeping -- consider this a success and ignore it.
1378 }
1379 }
1380 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001381 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001382 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001383 return finalState == OP_ACKNOWLEDGED;
1384 }
1385
1386 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001387 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001388 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001389 synchronized (mCurrentOpLock) {
1390 mCurrentOperations.put(token, OP_PENDING);
1391 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1392 mBackupHandler.sendMessageDelayed(msg, interval);
1393 }
Christopher Tate44a27902010-01-27 17:15:49 -08001394 }
1395
Christopher Tate043dadc2009-06-02 16:11:00 -07001396 // ----- Back up a set of applications via a worker thread -----
1397
Christopher Tate44a27902010-01-27 17:15:49 -08001398 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001399 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001400 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001401 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001402 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001403 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001404
Christopher Tate44a27902010-01-27 17:15:49 -08001405 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001406 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001407 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001408 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001409 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001410
1411 try {
1412 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1413 } catch (RemoteException e) {
1414 // can't happen; the transport is local
1415 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001416 }
1417
Christopher Tate043dadc2009-06-02 16:11:00 -07001418 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001419 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001420 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001421 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001422
Christopher Tate79588342009-06-30 16:11:49 -07001423 // Backups run at background priority
1424 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425
Christopher Tate043dadc2009-06-02 16:11:00 -07001426 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001427 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001428
Dan Egnor852f8e42009-09-30 11:20:45 -07001429 // If we haven't stored package manager metadata yet, we must init the transport.
1430 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1431 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001432 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001433 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001434 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001435 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001436 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001437 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001438 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001439 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001440 }
Dan Egnor01445162009-09-21 17:04:05 -07001441 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001442
1443 // The package manager doesn't have a proper <application> etc, but since
1444 // it's running here in the system process we can just set up its agent
1445 // directly and use a synthetic BackupRequest. We always run this pass
1446 // because it's cheap and this way we guarantee that we don't get out of
1447 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001448 if (status == BackupConstants.TRANSPORT_OK) {
1449 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1450 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001451 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001452 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1453 status = processOneBackup(pmRequest,
1454 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1455 }
Christopher Tate90967f42009-09-20 15:28:33 -07001456
Dan Egnor01445162009-09-21 17:04:05 -07001457 if (status == BackupConstants.TRANSPORT_OK) {
1458 // Now run all the backups in our queue
1459 status = doQueuedBackups(mTransport);
1460 }
1461
1462 if (status == BackupConstants.TRANSPORT_OK) {
1463 // Tell the transport to finish everything it has buffered
1464 status = mTransport.finishBackup();
1465 if (status == BackupConstants.TRANSPORT_OK) {
1466 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001467 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001468 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001469 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001470 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001471 }
1472 }
1473
Dan Egnor01445162009-09-21 17:04:05 -07001474 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001475 // The backend reports that our dataset has been wiped. We need to
1476 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001477 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001478 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001479 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001480 }
1481 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001482 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001483 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001484 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001485 // If everything actually went through and this is the first time we've
1486 // done a backup, we can now record what the current backup dataset token
1487 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001488 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001489 try {
1490 mCurrentToken = mTransport.getCurrentRestoreSet();
1491 } catch (RemoteException e) { /* cannot happen */ }
1492 writeRestoreTokens();
1493 }
1494
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001495 // If things went wrong, we need to re-stage the apps we had expected
1496 // to be backing up in this pass. This journals the package names in
1497 // the current active pending-backup file, not in the we are holding
1498 // here in mJournal.
1499 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001500 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001501 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001502 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001503 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001504
1505 // We also want to reset the backup schedule based on whatever
1506 // the transport suggests by way of retry/backoff time.
1507 try {
1508 startBackupAlarmsLocked(mTransport.requestBackupTime());
1509 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001510 }
1511
1512 // Either backup was successful, in which case we of course do not need
1513 // this pass's journal any more; or it failed, in which case we just
1514 // re-enqueued all of these packages in the current active journal.
1515 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001516 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001517 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001518 }
1519
Christopher Tatec2af5d32010-02-02 15:18:58 -08001520 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001521 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001522 backupNow();
1523 }
1524
Dan Egnorbb9001c2009-07-27 12:20:13 -07001525 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001526 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001527 }
1528
Dan Egnor01445162009-09-21 17:04:05 -07001529 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001530 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001531 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001532
Christopher Tatec28083a2010-12-14 16:16:44 -08001533 // Verify that the requested app exists; it might be something that
1534 // requested a backup but was then uninstalled. The request was
1535 // journalled and rather than tamper with the journal it's safer
1536 // to sanity-check here.
1537 try {
1538 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1539 } catch (NameNotFoundException e) {
1540 Slog.d(TAG, "Package does not exist; skipping");
1541 continue;
1542 }
1543
Christopher Tate043dadc2009-06-02 16:11:00 -07001544 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001545 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001546 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001547 agent = bindToAgentSynchronous(request.appInfo,
1548 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001549 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001550 int result = processOneBackup(request, agent, transport);
1551 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001552 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001553 } catch (SecurityException ex) {
1554 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001556 } finally {
1557 try { // unbind even on timeout, just in case
1558 mActivityManager.unbindBackupAgent(request.appInfo);
1559 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001560 }
1561 }
Dan Egnor01445162009-09-21 17:04:05 -07001562
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001563 mWakelock.setWorkSource(null);
1564
Dan Egnor01445162009-09-21 17:04:05 -07001565 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001566 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001567
Dan Egnor01445162009-09-21 17:04:05 -07001568 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1569 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001570 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001571 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001572
Dan Egnorbb9001c2009-07-27 12:20:13 -07001573 File savedStateName = new File(mStateDir, packageName);
1574 File backupDataName = new File(mDataDir, packageName + ".data");
1575 File newStateName = new File(mStateDir, packageName + ".new");
1576
1577 ParcelFileDescriptor savedState = null;
1578 ParcelFileDescriptor backupData = null;
1579 ParcelFileDescriptor newState = null;
1580
1581 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001582 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001583 try {
1584 // Look up the package info & signatures. This is first so that if it
1585 // throws an exception, there's no file setup yet that would need to
1586 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001587 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1588 // The metadata 'package' is synthetic
1589 packInfo = new PackageInfo();
1590 packInfo.packageName = packageName;
1591 } else {
1592 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001593 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001594 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001595
Christopher Tatec7b31e32009-06-10 15:49:30 -07001596 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001597 // the saved-state "file". This is by definition an incremental,
1598 // so we build a saved state file to pass.
1599 savedState = ParcelFileDescriptor.open(savedStateName,
1600 ParcelFileDescriptor.MODE_READ_ONLY |
1601 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001602
Dan Egnorbb9001c2009-07-27 12:20:13 -07001603 backupData = ParcelFileDescriptor.open(backupDataName,
1604 ParcelFileDescriptor.MODE_READ_WRITE |
1605 ParcelFileDescriptor.MODE_CREATE |
1606 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001607
Dan Egnorbb9001c2009-07-27 12:20:13 -07001608 newState = ParcelFileDescriptor.open(newStateName,
1609 ParcelFileDescriptor.MODE_READ_WRITE |
1610 ParcelFileDescriptor.MODE_CREATE |
1611 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001612
Christopher Tate44a27902010-01-27 17:15:49 -08001613 // Initiate the target's backup pass
1614 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001615 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001616 boolean success = waitUntilOperationComplete(token);
1617
1618 if (!success) {
1619 // timeout -- bail out into the failed-transaction logic
1620 throw new RuntimeException("Backup timeout");
1621 }
1622
Dan Egnorbb9001c2009-07-27 12:20:13 -07001623 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001624 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001625 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001626 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001627 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001628 backupDataName.delete();
1629 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001630 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001631 } finally {
1632 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1633 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1634 try { if (newState != null) newState.close(); } catch (IOException e) {}
1635 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001636 synchronized (mCurrentOpLock) {
1637 mCurrentOperations.clear();
1638 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001639 }
1640
1641 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001642 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001643 try {
1644 int size = (int) backupDataName.length();
1645 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001646 if (result == BackupConstants.TRANSPORT_OK) {
1647 backupData = ParcelFileDescriptor.open(backupDataName,
1648 ParcelFileDescriptor.MODE_READ_ONLY);
1649 result = transport.performBackup(packInfo, backupData);
1650 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001651
Dan Egnor83861e72009-09-17 16:17:55 -07001652 // TODO - We call finishBackup() for each application backed up, because
1653 // we need to know now whether it succeeded or failed. Instead, we should
1654 // hold off on finishBackup() until the end, which implies holding off on
1655 // renaming *all* the output state files (see below) until that happens.
1656
Dan Egnor01445162009-09-21 17:04:05 -07001657 if (result == BackupConstants.TRANSPORT_OK) {
1658 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001659 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001660 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001661 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001662 }
1663
1664 // After successful transport, delete the now-stale data
1665 // and juggle the files so that next time we supply the agent
1666 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001667 if (result == BackupConstants.TRANSPORT_OK) {
1668 backupDataName.delete();
1669 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001670 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001671 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001672 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001673 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001674 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001675 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001676 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001677 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001678 } finally {
1679 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001680 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001681
Dan Egnor01445162009-09-21 17:04:05 -07001682 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001683 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001684 }
1685
Christopher Tatedf01dea2009-06-09 20:45:02 -07001686
Christopher Tate4a627c72011-04-01 14:43:32 -07001687 // ----- Full backup to a file/socket -----
1688
1689 class PerformFullBackupTask implements Runnable {
1690 ParcelFileDescriptor mOutputFile;
Christopher Tate7926a692011-07-11 11:31:57 -07001691 DeflaterOutputStream mDeflater;
Christopher Tate4a627c72011-04-01 14:43:32 -07001692 IFullBackupRestoreObserver mObserver;
1693 boolean mIncludeApks;
1694 boolean mIncludeShared;
1695 boolean mAllApps;
1696 String[] mPackages;
1697 AtomicBoolean mLatchObject;
1698 File mFilesDir;
1699 File mManifestFile;
1700
Christopher Tate7926a692011-07-11 11:31:57 -07001701 class FullBackupRunner implements Runnable {
1702 PackageInfo mPackage;
1703 IBackupAgent mAgent;
1704 ParcelFileDescriptor mPipe;
1705 int mToken;
1706 boolean mSendApk;
1707
1708 FullBackupRunner(PackageInfo pack, IBackupAgent agent, ParcelFileDescriptor pipe,
1709 int token, boolean sendApk) throws IOException {
1710 mPackage = pack;
1711 mAgent = agent;
1712 mPipe = ParcelFileDescriptor.dup(pipe.getFileDescriptor());
1713 mToken = token;
1714 mSendApk = sendApk;
1715 }
1716
1717 @Override
1718 public void run() {
1719 try {
1720 BackupDataOutput output = new BackupDataOutput(
1721 mPipe.getFileDescriptor());
1722
1723 if (DEBUG) Slog.d(TAG, "Writing manifest for " + mPackage.packageName);
1724 writeAppManifest(mPackage, mManifestFile, mSendApk);
1725 FullBackup.backupToTar(mPackage.packageName, null, null,
1726 mFilesDir.getAbsolutePath(),
1727 mManifestFile.getAbsolutePath(),
1728 output);
1729
1730 if (mSendApk) {
1731 writeApkToBackup(mPackage, output);
1732 }
1733
1734 if (DEBUG) Slog.d(TAG, "Calling doFullBackup()");
1735 prepareOperationTimeout(mToken, TIMEOUT_FULL_BACKUP_INTERVAL);
1736 mAgent.doFullBackup(mPipe, mToken, mBackupManagerBinder);
1737 } catch (IOException e) {
1738 Slog.e(TAG, "Error running full backup for " + mPackage.packageName);
1739 } catch (RemoteException e) {
1740 Slog.e(TAG, "Remote agent vanished during full backup of "
1741 + mPackage.packageName);
1742 } finally {
1743 try {
1744 mPipe.close();
1745 } catch (IOException e) {}
1746 }
1747 }
1748 }
1749
Christopher Tate4a627c72011-04-01 14:43:32 -07001750 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
1751 boolean includeApks, boolean includeShared,
1752 boolean doAllApps, String[] packages, AtomicBoolean latch) {
1753 mOutputFile = fd;
1754 mObserver = observer;
1755 mIncludeApks = includeApks;
1756 mIncludeShared = includeShared;
1757 mAllApps = doAllApps;
1758 mPackages = packages;
1759 mLatchObject = latch;
1760
1761 mFilesDir = new File("/data/system");
1762 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1763 }
1764
1765 @Override
1766 public void run() {
1767 final List<PackageInfo> packagesToBackup;
1768
Christopher Tateb0628bf2011-06-02 15:08:13 -07001769 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07001770 sendStartBackup();
1771
1772 // doAllApps supersedes the package set if any
1773 if (mAllApps) {
1774 packagesToBackup = mPackageManager.getInstalledPackages(
1775 PackageManager.GET_SIGNATURES);
1776 } else {
1777 packagesToBackup = new ArrayList<PackageInfo>();
1778 for (String pkgName : mPackages) {
1779 try {
1780 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
1781 PackageManager.GET_SIGNATURES));
1782 } catch (NameNotFoundException e) {
1783 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
1784 }
1785 }
1786 }
1787
Christopher Tatea858cb02011-06-03 12:27:51 -07001788 // Cull any packages that have indicated that backups are not permitted.
1789 for (int i = 0; i < packagesToBackup.size(); ) {
1790 PackageInfo info = packagesToBackup.get(i);
1791 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
1792 packagesToBackup.remove(i);
1793 } else {
1794 i++;
1795 }
1796 }
1797
Christopher Tate7926a692011-07-11 11:31:57 -07001798 FileOutputStream ofstream = new FileOutputStream(mOutputFile.getFileDescriptor());
Christopher Tate7bdb0962011-07-13 19:30:21 -07001799
1800 // Set up the compression stage
Christopher Tate7926a692011-07-11 11:31:57 -07001801 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
1802 DeflaterOutputStream out = new DeflaterOutputStream(ofstream, deflater, true);
1803
Christopher Tate4a627c72011-04-01 14:43:32 -07001804 PackageInfo pkg = null;
1805 try {
Christopher Tate7bdb0962011-07-13 19:30:21 -07001806
1807 // !!! TODO: if using encryption, set up the encryption stage
1808 // and emit the tar header stating the password salt.
1809
1810 // Write the global file header. All strings are UTF-8 encoded; lines end
1811 // with a '\n' byte. Actual backup data begins immediately following the
1812 // final '\n'.
1813 //
1814 // line 1: "ANDROID BACKUP"
1815 // line 2: backup file format version, currently "1"
1816 // line 3: compressed? "0" if not compressed, "1" if compressed.
1817 // line 4: encryption salt? "-" if not encrypted, otherwise this
1818 // line contains the encryption salt with which the user-
1819 // supplied password is to be expanded, in hexadecimal.
1820 StringBuffer headerbuf = new StringBuffer(256);
1821 // !!! TODO: programmatically build the compressed / encryption salt fields
1822 headerbuf.append(BACKUP_FILE_HEADER_MAGIC);
1823 headerbuf.append("1\n1\n-\n");
1824
1825 try {
1826 byte[] header = headerbuf.toString().getBytes("UTF-8");
1827 ofstream.write(header);
1828 } catch (Exception e) {
1829 // Should never happen!
1830 Slog.e(TAG, "Unable to emit archive header", e);
1831 return;
1832 }
1833
Christopher Tateb0628bf2011-06-02 15:08:13 -07001834 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07001835 int N = packagesToBackup.size();
1836 for (int i = 0; i < N; i++) {
1837 pkg = packagesToBackup.get(i);
Christopher Tate7926a692011-07-11 11:31:57 -07001838 backupOnePackage(pkg, out);
Christopher Tateb0628bf2011-06-02 15:08:13 -07001839 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001840
Christopher Tateb0628bf2011-06-02 15:08:13 -07001841 // Finally, shared storage if requested
1842 if (mIncludeShared) {
1843 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07001844 }
1845 } catch (RemoteException e) {
1846 Slog.e(TAG, "App died during full backup");
1847 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07001848 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07001849 try {
Christopher Tate7926a692011-07-11 11:31:57 -07001850 out.close();
Christopher Tate4a627c72011-04-01 14:43:32 -07001851 mOutputFile.close();
1852 } catch (IOException e) {
1853 /* nothing we can do about this */
1854 }
1855 synchronized (mCurrentOpLock) {
1856 mCurrentOperations.clear();
1857 }
1858 synchronized (mLatchObject) {
1859 mLatchObject.set(true);
1860 mLatchObject.notifyAll();
1861 }
1862 sendEndBackup();
1863 mWakelock.release();
1864 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
1865 }
1866 }
1867
Christopher Tate7926a692011-07-11 11:31:57 -07001868 private void backupOnePackage(PackageInfo pkg, DeflaterOutputStream out)
1869 throws RemoteException {
Christopher Tateb0628bf2011-06-02 15:08:13 -07001870 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
1871
1872 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
1873 IApplicationThread.BACKUP_MODE_FULL);
1874 if (agent != null) {
Christopher Tate7926a692011-07-11 11:31:57 -07001875 ParcelFileDescriptor[] pipes = null;
Christopher Tateb0628bf2011-06-02 15:08:13 -07001876 try {
Christopher Tate7926a692011-07-11 11:31:57 -07001877 pipes = ParcelFileDescriptor.createPipe();
1878
Christopher Tateb0628bf2011-06-02 15:08:13 -07001879 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07001880 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07001881 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
1882 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
1883 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
1884
1885 sendOnBackupPackage(pkg.packageName);
1886
Christopher Tate7926a692011-07-11 11:31:57 -07001887 final int token = generateToken();
1888 FullBackupRunner runner = new FullBackupRunner(pkg, agent, pipes[1],
1889 token, sendApk);
1890 pipes[1].close(); // the runner has dup'd it
1891 pipes[1] = null;
1892 Thread t = new Thread(runner);
1893 t.start();
Christopher Tateb0628bf2011-06-02 15:08:13 -07001894
Christopher Tate7926a692011-07-11 11:31:57 -07001895 // Now pull data from the app and stuff it into the compressor
1896 try {
1897 FileInputStream raw = new FileInputStream(pipes[0].getFileDescriptor());
1898 DataInputStream in = new DataInputStream(raw);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001899
Christopher Tate7926a692011-07-11 11:31:57 -07001900 byte[] buffer = new byte[16 * 1024];
1901 int chunkTotal;
1902 while ((chunkTotal = in.readInt()) > 0) {
1903 while (chunkTotal > 0) {
1904 int toRead = (chunkTotal > buffer.length)
1905 ? buffer.length : chunkTotal;
1906 int nRead = in.read(buffer, 0, toRead);
1907 out.write(buffer, 0, nRead);
1908 chunkTotal -= nRead;
1909 }
1910 }
1911 } catch (IOException e) {
1912 Slog.i(TAG, "Caught exception reading from agent", e);
Christopher Tateb0628bf2011-06-02 15:08:13 -07001913 }
1914
Christopher Tateb0628bf2011-06-02 15:08:13 -07001915 if (!waitUntilOperationComplete(token)) {
1916 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
1917 } else {
Christopher Tate7926a692011-07-11 11:31:57 -07001918 if (DEBUG) Slog.d(TAG, "Full package backup success: " + pkg.packageName);
Christopher Tateb0628bf2011-06-02 15:08:13 -07001919 }
Christopher Tate7926a692011-07-11 11:31:57 -07001920
Christopher Tateb0628bf2011-06-02 15:08:13 -07001921 } catch (IOException e) {
1922 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
Christopher Tate7926a692011-07-11 11:31:57 -07001923 } finally {
1924 try {
1925 if (pipes != null) {
1926 if (pipes[0] != null) pipes[0].close();
1927 if (pipes[1] != null) pipes[1].close();
1928 }
1929
1930 // Apply a full sync/flush after each application's data
1931 out.flush();
1932 } catch (IOException e) {
1933 Slog.w(TAG, "Error bringing down backup stack");
1934 }
Christopher Tateb0628bf2011-06-02 15:08:13 -07001935 }
1936 } else {
1937 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
1938 }
1939 tearDown(pkg);
1940 }
1941
Christopher Tate79ec80d2011-06-24 14:58:49 -07001942 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
1943 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
1944 final String appSourceDir = pkg.applicationInfo.sourceDir;
1945 final String apkDir = new File(appSourceDir).getParent();
1946 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
1947 apkDir, appSourceDir, output);
1948
1949 // Save associated .obb content if it exists and we did save the apk
1950 // check for .obb and save those too
1951 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
1952 if (obbDir != null) {
1953 if (DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
1954 File[] obbFiles = obbDir.listFiles();
1955 if (obbFiles != null) {
1956 final String obbDirName = obbDir.getAbsolutePath();
1957 for (File obb : obbFiles) {
1958 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
1959 obbDirName, obb.getAbsolutePath(), output);
1960 }
1961 }
1962 }
1963 }
1964
Christopher Tateb0628bf2011-06-02 15:08:13 -07001965 private void backupSharedStorage() throws RemoteException {
1966 PackageInfo pkg = null;
1967 try {
1968 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
1969 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
1970 IApplicationThread.BACKUP_MODE_FULL);
1971 if (agent != null) {
1972 sendOnBackupPackage("Shared storage");
1973
1974 final int token = generateToken();
1975 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001976 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07001977 if (!waitUntilOperationComplete(token)) {
1978 Slog.e(TAG, "Full backup failed on shared storage");
1979 } else {
1980 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
1981 }
1982 } else {
1983 Slog.e(TAG, "Could not bind to shared storage backup agent");
1984 }
1985 } catch (NameNotFoundException e) {
1986 Slog.e(TAG, "Shared storage backup package not found");
1987 } finally {
1988 tearDown(pkg);
1989 }
1990 }
1991
Christopher Tate4a627c72011-04-01 14:43:32 -07001992 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
1993 throws IOException {
1994 // Manifest format. All data are strings ending in LF:
1995 // BACKUP_MANIFEST_VERSION, currently 1
1996 //
1997 // Version 1:
1998 // package name
1999 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07002000 // platform versionCode
2001 // getInstallerPackageName() for this package (maybe empty)
2002 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07002003 // number of signatures == N
2004 // N*: signature byte array in ascii format per Signature.toCharsString()
2005 StringBuilder builder = new StringBuilder(4096);
2006 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
2007
2008 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
2009 printer.println(pkg.packageName);
2010 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07002011 printer.println(Integer.toString(Build.VERSION.SDK_INT));
2012
2013 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
2014 printer.println((installerName != null) ? installerName : "");
2015
Christopher Tate4a627c72011-04-01 14:43:32 -07002016 printer.println(withApk ? "1" : "0");
2017 if (pkg.signatures == null) {
2018 printer.println("0");
2019 } else {
2020 printer.println(Integer.toString(pkg.signatures.length));
2021 for (Signature sig : pkg.signatures) {
2022 printer.println(sig.toCharsString());
2023 }
2024 }
2025
2026 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07002027 outstream.write(builder.toString().getBytes());
2028 outstream.close();
2029 }
2030
2031 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07002032 if (pkg != null) {
2033 final ApplicationInfo app = pkg.applicationInfo;
2034 if (app != null) {
2035 try {
2036 // unbind and tidy up even on timeout or failure, just in case
2037 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07002038
Christopher Tateb0628bf2011-06-02 15:08:13 -07002039 // The agent was running with a stub Application object, so shut it down.
2040 if (app.uid != Process.SYSTEM_UID) {
2041 if (DEBUG) Slog.d(TAG, "Backup complete, killing host process");
2042 mActivityManager.killApplicationProcess(app.processName, app.uid);
2043 } else {
2044 if (DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
2045 }
2046 } catch (RemoteException e) {
2047 Slog.d(TAG, "Lost app trying to shut down");
2048 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002049 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002050 }
2051 }
2052
2053 // wrappers for observer use
2054 void sendStartBackup() {
2055 if (mObserver != null) {
2056 try {
2057 mObserver.onStartBackup();
2058 } catch (RemoteException e) {
2059 Slog.w(TAG, "full backup observer went away: startBackup");
2060 mObserver = null;
2061 }
2062 }
2063 }
2064
2065 void sendOnBackupPackage(String name) {
2066 if (mObserver != null) {
2067 try {
2068 // TODO: use a more user-friendly name string
2069 mObserver.onBackupPackage(name);
2070 } catch (RemoteException e) {
2071 Slog.w(TAG, "full backup observer went away: backupPackage");
2072 mObserver = null;
2073 }
2074 }
2075 }
2076
2077 void sendEndBackup() {
2078 if (mObserver != null) {
2079 try {
2080 mObserver.onEndBackup();
2081 } catch (RemoteException e) {
2082 Slog.w(TAG, "full backup observer went away: endBackup");
2083 mObserver = null;
2084 }
2085 }
2086 }
2087 }
2088
2089
Christopher Tate75a99702011-05-18 16:28:19 -07002090 // ----- Full restore from a file/socket -----
2091
2092 // Description of a file in the restore datastream
2093 static class FileMetadata {
2094 String packageName; // name of the owning app
2095 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07002096 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07002097 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
2098 String path; // subpath within the semantic domain
2099 long mode; // e.g. 0666 (actually int)
2100 long mtime; // last mod time, UTC time_t (actually int)
2101 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002102
2103 @Override
2104 public String toString() {
2105 StringBuilder sb = new StringBuilder(128);
2106 sb.append("FileMetadata{");
2107 sb.append(packageName); sb.append(',');
2108 sb.append(type); sb.append(',');
2109 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
2110 sb.append(size);
2111 sb.append('}');
2112 return sb.toString();
2113 }
Christopher Tate75a99702011-05-18 16:28:19 -07002114 }
2115
2116 enum RestorePolicy {
2117 IGNORE,
2118 ACCEPT,
2119 ACCEPT_IF_APK
2120 }
2121
2122 class PerformFullRestoreTask implements Runnable {
2123 ParcelFileDescriptor mInputFile;
2124 IFullBackupRestoreObserver mObserver;
2125 AtomicBoolean mLatchObject;
2126 IBackupAgent mAgent;
2127 String mAgentPackage;
2128 ApplicationInfo mTargetApp;
2129 ParcelFileDescriptor[] mPipes = null;
2130
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002131 long mBytes;
2132
Christopher Tate75a99702011-05-18 16:28:19 -07002133 // possible handling states for a given package in the restore dataset
2134 final HashMap<String, RestorePolicy> mPackagePolicies
2135 = new HashMap<String, RestorePolicy>();
2136
2137 // installer package names for each encountered app, derived from the manifests
2138 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2139
2140 // Signatures for a given package found in its manifest file
2141 final HashMap<String, Signature[]> mManifestSignatures
2142 = new HashMap<String, Signature[]>();
2143
2144 // Packages we've already wiped data on when restoring their first file
2145 final HashSet<String> mClearedPackages = new HashSet<String>();
2146
2147 PerformFullRestoreTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
2148 AtomicBoolean latch) {
2149 mInputFile = fd;
2150 mObserver = observer;
2151 mLatchObject = latch;
2152 mAgent = null;
2153 mAgentPackage = null;
2154 mTargetApp = null;
2155
2156 // Which packages we've already wiped data on. We prepopulate this
2157 // with a whitelist of packages known to be unclearable.
2158 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002159 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002160
Christopher Tate75a99702011-05-18 16:28:19 -07002161 }
2162
2163 class RestoreFileRunnable implements Runnable {
2164 IBackupAgent mAgent;
2165 FileMetadata mInfo;
2166 ParcelFileDescriptor mSocket;
2167 int mToken;
2168
2169 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2170 ParcelFileDescriptor socket, int token) throws IOException {
2171 mAgent = agent;
2172 mInfo = info;
2173 mToken = token;
2174
2175 // This class is used strictly for process-local binder invocations. The
2176 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2177 // do not automatically get a 'dup'ed descriptor that we can can continue
2178 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2179 // before proceeding to do the restore.
2180 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2181 }
2182
2183 @Override
2184 public void run() {
2185 try {
2186 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2187 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2188 mToken, mBackupManagerBinder);
2189 } catch (RemoteException e) {
2190 // never happens; this is used strictly for local binder calls
2191 }
2192 }
2193 }
2194
2195 @Override
2196 public void run() {
2197 Slog.i(TAG, "--- Performing full-dataset restore ---");
2198 sendStartRestore();
2199
Christopher Tateb0628bf2011-06-02 15:08:13 -07002200 // Are we able to restore shared-storage data?
2201 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2202 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2203 }
2204
Christopher Tate75a99702011-05-18 16:28:19 -07002205 try {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002206 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002207 byte[] buffer = new byte[32 * 1024];
Christopher Tate7926a692011-07-11 11:31:57 -07002208 FileInputStream rawInStream = new FileInputStream(mInputFile.getFileDescriptor());
Christopher Tate7bdb0962011-07-13 19:30:21 -07002209
2210 // First, parse out the unencrypted/uncompressed header
2211 boolean compressed = false;
2212 boolean encrypted = false;
2213 final InputStream in;
2214
2215 boolean okay = false;
2216 final int headerLen = BACKUP_FILE_HEADER_MAGIC.length();
2217 byte[] streamHeader = new byte[headerLen];
2218 try {
2219 int got;
2220 if ((got = rawInStream.read(streamHeader, 0, headerLen)) == headerLen) {
2221 byte[] magicBytes = BACKUP_FILE_HEADER_MAGIC.getBytes("UTF-8");
2222 if (Arrays.equals(magicBytes, streamHeader)) {
2223 // okay, header looks good. now parse out the rest of the fields.
2224 String s = readHeaderLine(rawInStream);
2225 if (Integer.parseInt(s) == BACKUP_FILE_VERSION) {
2226 // okay, it's a version we recognize
2227 s = readHeaderLine(rawInStream);
2228 compressed = (Integer.parseInt(s) != 0);
2229 s = readHeaderLine(rawInStream);
2230 if (!s.startsWith("-")) {
2231 encrypted = true;
2232 // TODO: parse out the salt here and process with the user pw
2233 }
2234 okay = true;
2235 } else Slog.e(TAG, "Wrong header version: " + s);
2236 } else Slog.e(TAG, "Didn't read the right header magic");
2237 } else Slog.e(TAG, "Only read " + got + " bytes of header");
2238 } catch (NumberFormatException e) {
2239 Slog.e(TAG, "Can't parse restore data header");
2240 }
2241
2242 if (!okay) {
2243 Slog.e(TAG, "Invalid restore data; aborting.");
2244 return;
2245 }
2246
2247 // okay, use the right stream layer based on compression
2248 in = (compressed) ? new InflaterInputStream(rawInStream) : rawInStream;
Christopher Tate75a99702011-05-18 16:28:19 -07002249
2250 boolean didRestore;
2251 do {
Christopher Tate7926a692011-07-11 11:31:57 -07002252 didRestore = restoreOneFile(in, buffer);
Christopher Tate75a99702011-05-18 16:28:19 -07002253 } while (didRestore);
2254
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002255 if (DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate7bdb0962011-07-13 19:30:21 -07002256 } catch (IOException e) {
2257 Slog.e(TAG, "Unable to read restore input");
Christopher Tate75a99702011-05-18 16:28:19 -07002258 } finally {
2259 tearDownPipes();
2260 tearDownAgent(mTargetApp);
2261
2262 try {
2263 mInputFile.close();
2264 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002265 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002266 /* nothing we can do about this */
2267 }
2268 synchronized (mCurrentOpLock) {
2269 mCurrentOperations.clear();
2270 }
2271 synchronized (mLatchObject) {
2272 mLatchObject.set(true);
2273 mLatchObject.notifyAll();
2274 }
2275 sendEndRestore();
2276 mWakelock.release();
2277 if (DEBUG) Slog.d(TAG, "Full restore pass complete.");
2278 }
2279 }
2280
Christopher Tate7bdb0962011-07-13 19:30:21 -07002281 String readHeaderLine(InputStream in) throws IOException {
2282 int c;
2283 StringBuffer buffer = new StringBuffer(80);
2284 while ((c = in.read()) >= 0) {
2285 if (c == '\n') break; // consume and discard the newlines
2286 buffer.append((char)c);
2287 }
2288 return buffer.toString();
2289 }
2290
Christopher Tate75a99702011-05-18 16:28:19 -07002291 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2292 FileMetadata info;
2293 try {
2294 info = readTarHeaders(instream);
2295 if (info != null) {
2296 if (DEBUG) {
2297 dumpFileMetadata(info);
2298 }
2299
2300 final String pkg = info.packageName;
2301 if (!pkg.equals(mAgentPackage)) {
2302 // okay, change in package; set up our various
2303 // bookkeeping if we haven't seen it yet
2304 if (!mPackagePolicies.containsKey(pkg)) {
2305 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2306 }
2307
2308 // Clean up the previous agent relationship if necessary,
2309 // and let the observer know we're considering a new app.
2310 if (mAgent != null) {
2311 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2312 tearDownPipes();
2313 tearDownAgent(mTargetApp);
2314 mTargetApp = null;
2315 mAgentPackage = null;
2316 }
2317 }
2318
2319 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2320 mPackagePolicies.put(pkg, readAppManifest(info, instream));
2321 mPackageInstallers.put(pkg, info.installerPackageName);
2322 // We've read only the manifest content itself at this point,
2323 // so consume the footer before looping around to the next
2324 // input file
2325 skipTarPadding(info.size, instream);
2326 sendOnRestorePackage(pkg);
2327 } else {
2328 // Non-manifest, so it's actual file data. Is this a package
2329 // we're ignoring?
2330 boolean okay = true;
2331 RestorePolicy policy = mPackagePolicies.get(pkg);
2332 switch (policy) {
2333 case IGNORE:
2334 okay = false;
2335 break;
2336
2337 case ACCEPT_IF_APK:
2338 // If we're in accept-if-apk state, then the first file we
2339 // see MUST be the apk.
2340 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2341 if (DEBUG) Slog.d(TAG, "APK file; installing");
2342 // Try to install the app.
2343 String installerName = mPackageInstallers.get(pkg);
2344 okay = installApk(info, installerName, instream);
2345 // good to go; promote to ACCEPT
2346 mPackagePolicies.put(pkg, (okay)
2347 ? RestorePolicy.ACCEPT
2348 : RestorePolicy.IGNORE);
2349 // At this point we've consumed this file entry
2350 // ourselves, so just strip the tar footer and
2351 // go on to the next file in the input stream
2352 skipTarPadding(info.size, instream);
2353 return true;
2354 } else {
2355 // File data before (or without) the apk. We can't
2356 // handle it coherently in this case so ignore it.
2357 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2358 okay = false;
2359 }
2360 break;
2361
2362 case ACCEPT:
2363 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2364 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
2365 // we can take the data without the apk, so we
2366 // *want* to do so. skip the apk by declaring this
2367 // one file not-okay without changing the restore
2368 // policy for the package.
2369 okay = false;
2370 }
2371 break;
2372
2373 default:
2374 // Something has gone dreadfully wrong when determining
2375 // the restore policy from the manifest. Ignore the
2376 // rest of this package's data.
2377 Slog.e(TAG, "Invalid policy from manifest");
2378 okay = false;
2379 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2380 break;
2381 }
2382
2383 // If the policy is satisfied, go ahead and set up to pipe the
2384 // data to the agent.
2385 if (DEBUG && okay && mAgent != null) {
2386 Slog.i(TAG, "Reusing existing agent instance");
2387 }
2388 if (okay && mAgent == null) {
2389 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
2390
2391 try {
2392 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
2393
2394 // If we haven't sent any data to this app yet, we probably
2395 // need to clear it first. Check that.
2396 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002397 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07002398 // responsible for coherently managing a full
2399 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07002400 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07002401 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
2402 clearApplicationDataSynchronous(pkg);
2403 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002404 if (DEBUG) Slog.d(TAG, "backup agent ("
2405 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07002406 }
2407 mClearedPackages.add(pkg);
2408 } else {
2409 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
2410 }
2411
2412 // All set; now set up the IPC and launch the agent
2413 setUpPipes();
2414 mAgent = bindToAgentSynchronous(mTargetApp,
2415 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
2416 mAgentPackage = pkg;
2417 } catch (IOException e) {
2418 // fall through to error handling
2419 } catch (NameNotFoundException e) {
2420 // fall through to error handling
2421 }
2422
2423 if (mAgent == null) {
2424 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
2425 okay = false;
2426 tearDownPipes();
2427 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2428 }
2429 }
2430
2431 // Sanity check: make sure we never give data to the wrong app. This
2432 // should never happen but a little paranoia here won't go amiss.
2433 if (okay && !pkg.equals(mAgentPackage)) {
2434 Slog.e(TAG, "Restoring data for " + pkg
2435 + " but agent is for " + mAgentPackage);
2436 okay = false;
2437 }
2438
2439 // At this point we have an agent ready to handle the full
2440 // restore data as well as a pipe for sending data to
2441 // that agent. Tell the agent to start reading from the
2442 // pipe.
2443 if (okay) {
2444 boolean agentSuccess = true;
2445 long toCopy = info.size;
2446 final int token = generateToken();
2447 try {
2448 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
2449 + info.path);
2450 prepareOperationTimeout(token,
2451 TIMEOUT_FULL_BACKUP_INTERVAL);
2452 // fire up the app's agent listening on the socket. If
2453 // the agent is running in the system process we can't
2454 // just invoke it asynchronously, so we provide a thread
2455 // for it here.
2456 if (mTargetApp.processName.equals("system")) {
2457 Slog.d(TAG, "system process agent - spinning a thread");
2458 RestoreFileRunnable runner = new RestoreFileRunnable(
2459 mAgent, info, mPipes[0], token);
2460 new Thread(runner).start();
2461 } else {
2462 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
2463 info.domain, info.path, info.mode, info.mtime,
2464 token, mBackupManagerBinder);
2465 }
2466 } catch (IOException e) {
2467 // couldn't dup the socket for a process-local restore
2468 Slog.d(TAG, "Couldn't establish restore");
2469 agentSuccess = false;
2470 okay = false;
2471 } catch (RemoteException e) {
2472 // whoops, remote agent went away. We'll eat the content
2473 // ourselves, then, and not copy it over.
2474 Slog.e(TAG, "Agent crashed during full restore");
2475 agentSuccess = false;
2476 okay = false;
2477 }
2478
2479 // Copy over the data if the agent is still good
2480 if (okay) {
2481 boolean pipeOkay = true;
2482 FileOutputStream pipe = new FileOutputStream(
2483 mPipes[1].getFileDescriptor());
2484 if (DEBUG) Slog.d(TAG, "Piping data to agent");
2485 while (toCopy > 0) {
2486 int toRead = (toCopy > buffer.length)
2487 ? buffer.length : (int)toCopy;
2488 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002489 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002490 if (nRead <= 0) break;
2491 toCopy -= nRead;
2492
2493 // send it to the output pipe as long as things
2494 // are still good
2495 if (pipeOkay) {
2496 try {
2497 pipe.write(buffer, 0, nRead);
2498 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002499 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002500 pipeOkay = false;
2501 }
2502 }
2503 }
2504
2505 // done sending that file! Now we just need to consume
2506 // the delta from info.size to the end of block.
2507 skipTarPadding(info.size, instream);
2508
2509 // and now that we've sent it all, wait for the remote
2510 // side to acknowledge receipt
2511 agentSuccess = waitUntilOperationComplete(token);
2512 }
2513
2514 // okay, if the remote end failed at any point, deal with
2515 // it by ignoring the rest of the restore on it
2516 if (!agentSuccess) {
2517 mBackupHandler.removeMessages(MSG_TIMEOUT);
2518 tearDownPipes();
2519 tearDownAgent(mTargetApp);
2520 mAgent = null;
2521 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2522 }
2523 }
2524
2525 // Problems setting up the agent communication, or an already-
2526 // ignored package: skip to the next tar stream entry by
2527 // reading and discarding this file.
2528 if (!okay) {
2529 if (DEBUG) Slog.d(TAG, "[discarding file content]");
2530 long bytesToConsume = (info.size + 511) & ~511;
2531 while (bytesToConsume > 0) {
2532 int toRead = (bytesToConsume > buffer.length)
2533 ? buffer.length : (int)bytesToConsume;
2534 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002535 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002536 if (nRead <= 0) break;
2537 bytesToConsume -= nRead;
2538 }
2539 }
2540 }
2541 }
2542 } catch (IOException e) {
2543 Slog.w(TAG, "io exception on restore socket read", e);
2544 // treat as EOF
2545 info = null;
2546 }
2547
2548 return (info != null);
2549 }
2550
2551 void setUpPipes() throws IOException {
2552 mPipes = ParcelFileDescriptor.createPipe();
2553 }
2554
2555 void tearDownPipes() {
2556 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002557 try {
2558 mPipes[0].close();
2559 mPipes[0] = null;
2560 mPipes[1].close();
2561 mPipes[1] = null;
2562 } catch (IOException e) {
2563 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002564 }
2565 mPipes = null;
2566 }
2567 }
2568
2569 void tearDownAgent(ApplicationInfo app) {
2570 if (mAgent != null) {
2571 try {
2572 // unbind and tidy up even on timeout or failure, just in case
2573 mActivityManager.unbindBackupAgent(app);
2574
2575 // The agent was running with a stub Application object, so shut it down.
2576 // !!! We hardcode the confirmation UI's package name here rather than use a
2577 // manifest flag! TODO something less direct.
2578 if (app.uid != Process.SYSTEM_UID
2579 && !app.packageName.equals("com.android.backupconfirm")) {
2580 if (DEBUG) Slog.d(TAG, "Killing host process");
2581 mActivityManager.killApplicationProcess(app.processName, app.uid);
2582 } else {
2583 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
2584 }
2585 } catch (RemoteException e) {
2586 Slog.d(TAG, "Lost app trying to shut down");
2587 }
2588 mAgent = null;
2589 }
2590 }
2591
2592 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
2593 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07002594 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07002595 int mResult;
2596
2597 public void reset() {
2598 synchronized (mDone) {
2599 mDone.set(false);
2600 }
2601 }
2602
2603 public void waitForCompletion() {
2604 synchronized (mDone) {
2605 while (mDone.get() == false) {
2606 try {
2607 mDone.wait();
2608 } catch (InterruptedException e) { }
2609 }
2610 }
2611 }
2612
2613 int getResult() {
2614 return mResult;
2615 }
2616
2617 @Override
2618 public void packageInstalled(String packageName, int returnCode)
2619 throws RemoteException {
2620 synchronized (mDone) {
2621 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07002622 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07002623 mDone.set(true);
2624 mDone.notifyAll();
2625 }
2626 }
2627 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002628
2629 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
2630 final AtomicBoolean mDone = new AtomicBoolean();
2631 int mResult;
2632
2633 public void reset() {
2634 synchronized (mDone) {
2635 mDone.set(false);
2636 }
2637 }
2638
2639 public void waitForCompletion() {
2640 synchronized (mDone) {
2641 while (mDone.get() == false) {
2642 try {
2643 mDone.wait();
2644 } catch (InterruptedException e) { }
2645 }
2646 }
2647 }
2648
2649 @Override
2650 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
2651 synchronized (mDone) {
2652 mResult = returnCode;
2653 mDone.set(true);
2654 mDone.notifyAll();
2655 }
2656 }
2657 }
2658
Christopher Tate75a99702011-05-18 16:28:19 -07002659 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07002660 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07002661
2662 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
2663 boolean okay = true;
2664
2665 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
2666
2667 // The file content is an .apk file. Copy it out to a staging location and
2668 // attempt to install it.
2669 File apkFile = new File(mDataDir, info.packageName);
2670 try {
2671 FileOutputStream apkStream = new FileOutputStream(apkFile);
2672 byte[] buffer = new byte[32 * 1024];
2673 long size = info.size;
2674 while (size > 0) {
2675 long toRead = (buffer.length < size) ? buffer.length : size;
2676 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002677 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002678 apkStream.write(buffer, 0, didRead);
2679 size -= didRead;
2680 }
2681 apkStream.close();
2682
2683 // make sure the installer can read it
2684 apkFile.setReadable(true, false);
2685
2686 // Now install it
2687 Uri packageUri = Uri.fromFile(apkFile);
2688 mInstallObserver.reset();
2689 mPackageManager.installPackage(packageUri, mInstallObserver,
2690 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
2691 mInstallObserver.waitForCompletion();
2692
2693 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
2694 // The only time we continue to accept install of data even if the
2695 // apk install failed is if we had already determined that we could
2696 // accept the data regardless.
2697 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
2698 okay = false;
2699 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002700 } else {
2701 // Okay, the install succeeded. Make sure it was the right app.
2702 boolean uninstall = false;
2703 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
2704 Slog.w(TAG, "Restore stream claimed to include apk for "
2705 + info.packageName + " but apk was really "
2706 + mInstallObserver.mPackageName);
2707 // delete the package we just put in place; it might be fraudulent
2708 okay = false;
2709 uninstall = true;
2710 } else {
2711 try {
2712 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
2713 PackageManager.GET_SIGNATURES);
2714 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2715 Slog.w(TAG, "Restore stream contains apk of package "
2716 + info.packageName + " but it disallows backup/restore");
2717 okay = false;
2718 } else {
2719 // So far so good -- do the signatures match the manifest?
2720 Signature[] sigs = mManifestSignatures.get(info.packageName);
2721 if (!signaturesMatch(sigs, pkg)) {
2722 Slog.w(TAG, "Installed app " + info.packageName
2723 + " signatures do not match restore manifest");
2724 okay = false;
2725 uninstall = true;
2726 }
2727 }
2728 } catch (NameNotFoundException e) {
2729 Slog.w(TAG, "Install of package " + info.packageName
2730 + " succeeded but now not found");
2731 okay = false;
2732 }
2733 }
2734
2735 // If we're not okay at this point, we need to delete the package
2736 // that we just installed.
2737 if (uninstall) {
2738 mDeleteObserver.reset();
2739 mPackageManager.deletePackage(mInstallObserver.mPackageName,
2740 mDeleteObserver, 0);
2741 mDeleteObserver.waitForCompletion();
2742 }
Christopher Tate75a99702011-05-18 16:28:19 -07002743 }
2744 } catch (IOException e) {
2745 Slog.e(TAG, "Unable to transcribe restored apk for install");
2746 okay = false;
2747 } finally {
2748 apkFile.delete();
2749 }
2750
2751 return okay;
2752 }
2753
2754 // Given an actual file content size, consume the post-content padding mandated
2755 // by the tar format.
2756 void skipTarPadding(long size, InputStream instream) throws IOException {
2757 long partial = (size + 512) % 512;
2758 if (partial > 0) {
2759 byte[] buffer = new byte[512];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002760 int nRead = instream.read(buffer, 0, 512 - (int)partial);
2761 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002762 }
2763 }
2764
2765 // Returns a policy constant; takes a buffer arg to reduce memory churn
2766 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
2767 throws IOException {
2768 // Fail on suspiciously large manifest files
2769 if (info.size > 64 * 1024) {
2770 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
2771 }
2772 byte[] buffer = new byte[(int) info.size];
2773 int nRead = 0;
2774 while (nRead < info.size) {
2775 nRead += instream.read(buffer, nRead, (int)info.size - nRead);
2776 }
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002777 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002778
2779 RestorePolicy policy = RestorePolicy.IGNORE;
2780 String[] str = new String[1];
2781 int offset = 0;
2782
2783 try {
2784 offset = extractLine(buffer, offset, str);
2785 int version = Integer.parseInt(str[0]);
2786 if (version == BACKUP_MANIFEST_VERSION) {
2787 offset = extractLine(buffer, offset, str);
2788 String manifestPackage = str[0];
2789 // TODO: handle <original-package>
2790 if (manifestPackage.equals(info.packageName)) {
2791 offset = extractLine(buffer, offset, str);
2792 version = Integer.parseInt(str[0]); // app version
2793 offset = extractLine(buffer, offset, str);
2794 int platformVersion = Integer.parseInt(str[0]);
2795 offset = extractLine(buffer, offset, str);
2796 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
2797 offset = extractLine(buffer, offset, str);
2798 boolean hasApk = str[0].equals("1");
2799 offset = extractLine(buffer, offset, str);
2800 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07002801 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002802 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07002803 for (int i = 0; i < numSigs; i++) {
2804 offset = extractLine(buffer, offset, str);
2805 sigs[i] = new Signature(str[0]);
2806 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002807 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07002808
2809 // Okay, got the manifest info we need...
2810 try {
Christopher Tate75a99702011-05-18 16:28:19 -07002811 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2812 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07002813 // Fall through to IGNORE if the app explicitly disallows backup
2814 final int flags = pkgInfo.applicationInfo.flags;
2815 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
2816 // Verify signatures against any installed version; if they
2817 // don't match, then we fall though and ignore the data. The
2818 // signatureMatch() method explicitly ignores the signature
2819 // check for packages installed on the system partition, because
2820 // such packages are signed with the platform cert instead of
2821 // the app developer's cert, so they're different on every
2822 // device.
2823 if (signaturesMatch(sigs, pkgInfo)) {
2824 if (pkgInfo.versionCode >= version) {
2825 Slog.i(TAG, "Sig + version match; taking data");
2826 policy = RestorePolicy.ACCEPT;
2827 } else {
2828 // The data is from a newer version of the app than
2829 // is presently installed. That means we can only
2830 // use it if the matching apk is also supplied.
2831 Slog.d(TAG, "Data version " + version
2832 + " is newer than installed version "
2833 + pkgInfo.versionCode + " - requiring apk");
2834 policy = RestorePolicy.ACCEPT_IF_APK;
2835 }
Christopher Tate75a99702011-05-18 16:28:19 -07002836 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07002837 Slog.w(TAG, "Restore manifest signatures do not match "
2838 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07002839 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002840 } else {
2841 if (DEBUG) Slog.i(TAG, "Restore manifest from "
2842 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07002843 }
2844 } catch (NameNotFoundException e) {
2845 // Okay, the target app isn't installed. We can process
2846 // the restore properly only if the dataset provides the
2847 // apk file and we can successfully install it.
2848 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
2849 + " not installed; requiring apk in dataset");
2850 policy = RestorePolicy.ACCEPT_IF_APK;
2851 }
2852
2853 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
2854 Slog.i(TAG, "Cannot restore package " + info.packageName
2855 + " without the matching .apk");
2856 }
2857 } else {
2858 Slog.i(TAG, "Missing signature on backed-up package "
2859 + info.packageName);
2860 }
2861 } else {
2862 Slog.i(TAG, "Expected package " + info.packageName
2863 + " but restore manifest claims " + manifestPackage);
2864 }
2865 } else {
2866 Slog.i(TAG, "Unknown restore manifest version " + version
2867 + " for package " + info.packageName);
2868 }
2869 } catch (NumberFormatException e) {
2870 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
2871 }
2872
2873 return policy;
2874 }
2875
2876 // Builds a line from a byte buffer starting at 'offset', and returns
2877 // the index of the next unconsumed data in the buffer.
2878 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
2879 final int end = buffer.length;
2880 if (offset >= end) throw new IOException("Incomplete data");
2881
2882 int pos;
2883 for (pos = offset; pos < end; pos++) {
2884 byte c = buffer[pos];
2885 // at LF we declare end of line, and return the next char as the
2886 // starting point for the next time through
2887 if (c == '\n') {
2888 break;
2889 }
2890 }
2891 outStr[0] = new String(buffer, offset, pos - offset);
2892 pos++; // may be pointing an extra byte past the end but that's okay
2893 return pos;
2894 }
2895
2896 void dumpFileMetadata(FileMetadata info) {
2897 if (DEBUG) {
2898 StringBuilder b = new StringBuilder(128);
2899
2900 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07002901 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07002902 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
2903 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
2904 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
2905 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
2906 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
2907 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
2908 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
2909 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
2910 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
2911 b.append(String.format(" %9d ", info.size));
2912
2913 Date stamp = new Date(info.mtime);
2914 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
2915
2916 b.append(info.packageName);
2917 b.append(" :: ");
2918 b.append(info.domain);
2919 b.append(" :: ");
2920 b.append(info.path);
2921
2922 Slog.i(TAG, b.toString());
2923 }
2924 }
2925 // Consume a tar file header block [sequence] and accumulate the relevant metadata
2926 FileMetadata readTarHeaders(InputStream instream) throws IOException {
2927 byte[] block = new byte[512];
2928 FileMetadata info = null;
2929
2930 boolean gotHeader = readTarHeader(instream, block);
2931 if (gotHeader) {
2932 // okay, presume we're okay, and extract the various metadata
2933 info = new FileMetadata();
2934 info.size = extractRadix(block, 124, 12, 8);
2935 info.mtime = extractRadix(block, 136, 12, 8);
2936 info.mode = extractRadix(block, 100, 8, 8);
2937
2938 info.path = extractString(block, 345, 155); // prefix
2939 String path = extractString(block, 0, 100);
2940 if (path.length() > 0) {
2941 if (info.path.length() > 0) info.path += '/';
2942 info.path += path;
2943 }
2944
2945 // tar link indicator field: 1 byte at offset 156 in the header.
2946 int typeChar = block[156];
2947 if (typeChar == 'x') {
2948 // pax extended header, so we need to read that
2949 gotHeader = readPaxExtendedHeader(instream, info);
2950 if (gotHeader) {
2951 // and after a pax extended header comes another real header -- read
2952 // that to find the real file type
2953 gotHeader = readTarHeader(instream, block);
2954 }
2955 if (!gotHeader) throw new IOException("Bad or missing pax header");
2956
2957 typeChar = block[156];
2958 }
2959
2960 switch (typeChar) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002961 case '0': info.type = BackupAgent.TYPE_FILE; break;
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002962 case '5': {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002963 info.type = BackupAgent.TYPE_DIRECTORY;
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002964 if (info.size != 0) {
2965 Slog.w(TAG, "Directory entry with nonzero size in header");
2966 info.size = 0;
2967 }
2968 break;
2969 }
Christopher Tate75a99702011-05-18 16:28:19 -07002970 case 0: {
2971 // presume EOF
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002972 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
Christopher Tate75a99702011-05-18 16:28:19 -07002973 return null;
2974 }
2975 default: {
2976 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
2977 throw new IOException("Unknown entity type " + typeChar);
2978 }
2979 }
2980
2981 // Parse out the path
2982 //
2983 // first: apps/shared/unrecognized
2984 if (FullBackup.SHARED_PREFIX.regionMatches(0,
2985 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
2986 // File in shared storage. !!! TODO: implement this.
2987 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tateb0628bf2011-06-02 15:08:13 -07002988 info.packageName = "com.android.sharedstoragebackup";
Christopher Tate75a99702011-05-18 16:28:19 -07002989 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002990 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
Christopher Tate75a99702011-05-18 16:28:19 -07002991 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
2992 info.path, 0, FullBackup.APPS_PREFIX.length())) {
2993 // App content! Parse out the package name and domain
2994
2995 // strip the apps/ prefix
2996 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
2997
2998 // extract the package name
2999 int slash = info.path.indexOf('/');
3000 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
3001 info.packageName = info.path.substring(0, slash);
3002 info.path = info.path.substring(slash+1);
3003
3004 // if it's a manifest we're done, otherwise parse out the domains
3005 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
3006 slash = info.path.indexOf('/');
3007 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
3008 info.domain = info.path.substring(0, slash);
3009 // validate that it's one of the domains we understand
3010 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
3011 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
3012 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
3013 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
3014 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
3015 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
3016 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
3017 throw new IOException("Unrecognized domain " + info.domain);
3018 }
3019
3020 info.path = info.path.substring(slash + 1);
3021 }
3022 }
3023 }
3024 return info;
3025 }
3026
3027 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
3028 int nRead = instream.read(block, 0, 512);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003029 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003030 if (nRead > 0 && nRead != 512) {
3031 // if we read only a partial block, then things are
3032 // clearly screwed up. terminate the restore.
3033 throw new IOException("Partial header block: " + nRead);
3034 }
3035 return (nRead > 0);
3036 }
3037
3038 // overwrites 'info' fields based on the pax extended header
3039 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
3040 throws IOException {
3041 // We should never see a pax extended header larger than this
3042 if (info.size > 32*1024) {
3043 Slog.w(TAG, "Suspiciously large pax header size " + info.size
3044 + " - aborting");
3045 throw new IOException("Sanity failure: pax header size " + info.size);
3046 }
3047
3048 // read whole blocks, not just the content size
3049 int numBlocks = (int)((info.size + 511) >> 9);
3050 byte[] data = new byte[numBlocks * 512];
3051 int nRead = instream.read(data);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07003052 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07003053 if (nRead != data.length) {
3054 return false;
3055 }
3056
3057 final int contentSize = (int) info.size;
3058 int offset = 0;
3059 do {
3060 // extract the line at 'offset'
3061 int eol = offset+1;
3062 while (eol < contentSize && data[eol] != ' ') eol++;
3063 if (eol >= contentSize) {
3064 // error: we just hit EOD looking for the end of the size field
3065 throw new IOException("Invalid pax data");
3066 }
3067 // eol points to the space between the count and the key
3068 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
3069 int key = eol + 1; // start of key=value
3070 eol = offset + linelen - 1; // trailing LF
3071 int value;
3072 for (value = key+1; data[value] != '=' && value <= eol; value++);
3073 if (value > eol) {
3074 throw new IOException("Invalid pax declaration");
3075 }
3076
3077 // pax requires that key/value strings be in UTF-8
3078 String keyStr = new String(data, key, value-key, "UTF-8");
3079 // -1 to strip the trailing LF
3080 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
3081
3082 if ("path".equals(keyStr)) {
3083 info.path = valStr;
3084 } else if ("size".equals(keyStr)) {
3085 info.size = Long.parseLong(valStr);
3086 } else {
3087 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
3088 }
3089
3090 offset += linelen;
3091 } while (offset < contentSize);
3092
3093 return true;
3094 }
3095
3096 long extractRadix(byte[] data, int offset, int maxChars, int radix)
3097 throws IOException {
3098 long value = 0;
3099 final int end = offset + maxChars;
3100 for (int i = offset; i < end; i++) {
3101 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003102 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07003103 if (b == 0 || b == ' ') break;
3104 if (b < '0' || b > ('0' + radix - 1)) {
3105 throw new IOException("Invalid number in header");
3106 }
3107 value = radix * value + (b - '0');
3108 }
3109 return value;
3110 }
3111
3112 String extractString(byte[] data, int offset, int maxChars) throws IOException {
3113 final int end = offset + maxChars;
3114 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07003115 // tar string fields terminate early with a NUL
3116 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07003117 return new String(data, offset, eos-offset, "US-ASCII");
3118 }
3119
3120 void sendStartRestore() {
3121 if (mObserver != null) {
3122 try {
3123 mObserver.onStartRestore();
3124 } catch (RemoteException e) {
3125 Slog.w(TAG, "full restore observer went away: startRestore");
3126 mObserver = null;
3127 }
3128 }
3129 }
3130
3131 void sendOnRestorePackage(String name) {
3132 if (mObserver != null) {
3133 try {
3134 // TODO: use a more user-friendly name string
3135 mObserver.onRestorePackage(name);
3136 } catch (RemoteException e) {
3137 Slog.w(TAG, "full restore observer went away: restorePackage");
3138 mObserver = null;
3139 }
3140 }
3141 }
3142
3143 void sendEndRestore() {
3144 if (mObserver != null) {
3145 try {
3146 mObserver.onEndRestore();
3147 } catch (RemoteException e) {
3148 Slog.w(TAG, "full restore observer went away: endRestore");
3149 mObserver = null;
3150 }
3151 }
3152 }
3153 }
3154
Christopher Tatedf01dea2009-06-09 20:45:02 -07003155 // ----- Restore handling -----
3156
Christopher Tate78dd4a72009-11-04 11:49:08 -08003157 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
3158 // If the target resides on the system partition, we allow it to restore
3159 // data from the like-named package in a restore set even if the signatures
3160 // do not match. (Unlike general applications, those flashed to the system
3161 // partition will be signed with the device's platform certificate, so on
3162 // different phones the same system app will have different signatures.)
3163 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003164 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08003165 return true;
3166 }
3167
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003168 // Allow unsigned apps, but not signed on one device and unsigned on the other
3169 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08003170 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003171 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07003172 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003173 if ((storedSigs == null || storedSigs.length == 0)
3174 && (deviceSigs == null || deviceSigs.length == 0)) {
3175 return true;
3176 }
3177 if (storedSigs == null || deviceSigs == null) {
3178 return false;
3179 }
3180
Christopher Tateabce4e82009-06-18 18:35:32 -07003181 // !!! TODO: this demands that every stored signature match one
3182 // that is present on device, and does not demand the converse.
3183 // Is this this right policy?
3184 int nStored = storedSigs.length;
3185 int nDevice = deviceSigs.length;
3186
3187 for (int i=0; i < nStored; i++) {
3188 boolean match = false;
3189 for (int j=0; j < nDevice; j++) {
3190 if (storedSigs[i].equals(deviceSigs[j])) {
3191 match = true;
3192 break;
3193 }
3194 }
3195 if (!match) {
3196 return false;
3197 }
3198 }
3199 return true;
3200 }
3201
Christopher Tate44a27902010-01-27 17:15:49 -08003202 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003203 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003204 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003205 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003206 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003207 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003208 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003209 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003210 private HashSet<String> mFilterSet;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003211
Christopher Tate5cbbf562009-06-22 16:44:51 -07003212 class RestoreRequest {
3213 public PackageInfo app;
3214 public int storedAppVersion;
3215
3216 RestoreRequest(PackageInfo _app, int _version) {
3217 app = _app;
3218 storedAppVersion = _version;
3219 }
3220 }
3221
Christopher Tate44a27902010-01-27 17:15:49 -08003222 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003223 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003224 boolean needFullBackup, String[] filterSet) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003225 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003226 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003227 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003228 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003229 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003230 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003231
Christopher Tate284f1bb2011-07-07 14:31:18 -07003232 if (filterSet != null) {
3233 mFilterSet = new HashSet<String>();
3234 for (String pkg : filterSet) {
3235 mFilterSet.add(pkg);
3236 }
3237 } else {
3238 mFilterSet = null;
3239 }
3240
Christopher Tate5cb400b2009-06-25 16:03:14 -07003241 try {
3242 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3243 } catch (RemoteException e) {
3244 // can't happen; the transport is local
3245 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003246 }
3247
Christopher Tatedf01dea2009-06-09 20:45:02 -07003248 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003249 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003250 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08003251 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate284f1bb2011-07-07 14:31:18 -07003252 + " mTargetPackage=" + mTargetPackage + " mFilterSet=" + mFilterSet
3253 + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003254
Christopher Tateb49ceb32010-02-08 16:22:24 -08003255 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003256 int error = -1; // assume error
3257
Dan Egnorefe52642009-06-24 00:16:33 -07003258 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07003259 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003260 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003261 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07003262
Dan Egnorefe52642009-06-24 00:16:33 -07003263 // Get the list of all packages which have backup enabled.
3264 // (Include the Package Manager metadata pseudo-package first.)
3265 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
3266 PackageInfo omPackage = new PackageInfo();
3267 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
3268 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003269
Dan Egnorefe52642009-06-24 00:16:33 -07003270 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003271 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07003272 // if there's a filter set, strip out anything that isn't
3273 // present before proceeding
3274 if (mFilterSet != null) {
3275 for (int i = agentPackages.size() - 1; i >= 0; i--) {
3276 final PackageInfo pkg = agentPackages.get(i);
3277 if (! mFilterSet.contains(pkg.packageName)) {
3278 agentPackages.remove(i);
3279 }
3280 }
3281 if (DEBUG) {
3282 Slog.i(TAG, "Post-filter package set for restore:");
3283 for (PackageInfo p : agentPackages) {
3284 Slog.i(TAG, " " + p);
3285 }
3286 }
3287 }
Christopher Tate84725812010-02-04 15:52:40 -08003288 restorePackages.addAll(agentPackages);
3289 } else {
3290 // Just one package to attempt restore of
3291 restorePackages.add(mTargetPackage);
3292 }
Dan Egnorefe52642009-06-24 00:16:33 -07003293
Christopher Tate7d562ec2009-06-25 18:03:43 -07003294 // let the observer know that we're running
3295 if (mObserver != null) {
3296 try {
3297 // !!! TODO: get an actual count from the transport after
3298 // its startRestore() runs?
3299 mObserver.restoreStarting(restorePackages.size());
3300 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003301 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003302 mObserver = null;
3303 }
3304 }
3305
Dan Egnor01445162009-09-21 17:04:05 -07003306 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
3307 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003308 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003309 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003310 return;
3311 }
3312
3313 String packageName = mTransport.nextRestorePackage();
3314 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003315 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003316 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003317 return;
3318 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003319 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003320 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003321 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07003322 return;
3323 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003324 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07003325 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003326 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003327 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003328 return;
3329 }
3330
3331 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08003332 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07003333 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07003334 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
3335 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07003336
Christopher Tate8c032472009-07-02 14:28:47 -07003337 // Verify that the backup set includes metadata. If not, we can't do
3338 // signature/version verification etc, so we simply do not proceed with
3339 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07003340 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003341 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003342 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003343 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07003344 return;
3345 }
3346
Christopher Tate7d562ec2009-06-25 18:03:43 -07003347 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07003348 for (;;) {
3349 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003350
Dan Egnorefe52642009-06-24 00:16:33 -07003351 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003352 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003353 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003354 return;
3355 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003356 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07003357 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003358 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003359
Christopher Tate7d562ec2009-06-25 18:03:43 -07003360 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07003361 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07003362 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07003363 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003364 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003365 mObserver = null;
3366 }
3367 }
3368
Dan Egnorefe52642009-06-24 00:16:33 -07003369 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
3370 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003371 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003372 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003373 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003374 continue;
3375 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003376
Dan Egnorbb9001c2009-07-27 12:20:13 -07003377 PackageInfo packageInfo;
3378 try {
3379 int flags = PackageManager.GET_SIGNATURES;
3380 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
3381 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003382 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003383 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003384 "Package missing on device");
3385 continue;
3386 }
3387
Dan Egnorefe52642009-06-24 00:16:33 -07003388 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08003389 // Data is from a "newer" version of the app than we have currently
3390 // installed. If the app has not declared that it is prepared to
3391 // handle this case, we do not attempt the restore.
3392 if ((packageInfo.applicationInfo.flags
3393 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
3394 String message = "Version " + metaInfo.versionCode
3395 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003396 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08003397 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
3398 packageName, message);
3399 continue;
3400 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003401 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08003402 + " > installed " + packageInfo.versionCode
3403 + " but restoreAnyVersion");
3404 }
Dan Egnorefe52642009-06-24 00:16:33 -07003405 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003406
Christopher Tate78dd4a72009-11-04 11:49:08 -08003407 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003408 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003409 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003410 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07003411 continue;
3412 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003413
Joe Onorato8a9b2202010-02-26 18:56:32 -08003414 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07003415 + " restore version [" + metaInfo.versionCode
3416 + "] is compatible with installed version ["
3417 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07003418
Christopher Tate3de55bc2010-03-12 17:28:08 -08003419 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07003420 IBackupAgent agent = bindToAgentSynchronous(
3421 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08003422 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07003423 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003424 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003425 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003426 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003427 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003428 }
3429
Christopher Tate5e1ab332009-09-01 20:32:49 -07003430 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07003431 try {
Chris Tate249345b2010-10-29 12:57:04 -07003432 processOneRestore(packageInfo, metaInfo.versionCode, agent,
3433 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003434 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07003435 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003436 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07003437 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07003438
3439 // The agent was probably running with a stub Application object,
3440 // which isn't a valid run mode for the main app logic. Shut
3441 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08003442 // usual full initialization. Note that this is only done for
3443 // full-system restores: when a single app has requested a restore,
3444 // it is explicitly not killed following that operation.
3445 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07003446 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003447 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003448 + packageInfo.applicationInfo.processName);
3449 mActivityManager.killApplicationProcess(
3450 packageInfo.applicationInfo.processName,
3451 packageInfo.applicationInfo.uid);
3452 }
Dan Egnorefe52642009-06-24 00:16:33 -07003453 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003454 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003455
3456 // if we get this far, report success to the observer
3457 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07003458 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003459 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003460 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003461 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003462 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003463 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003464
Dan Egnorefe52642009-06-24 00:16:33 -07003465 try {
3466 mTransport.finishRestore();
3467 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003468 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003469 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003470
3471 if (mObserver != null) {
3472 try {
3473 mObserver.restoreFinished(error);
3474 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003475 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003476 }
3477 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003478
Christopher Tate84725812010-02-04 15:52:40 -08003479 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08003480 // ancestral dataset, as well as the set of apps that are possibly
3481 // restoreable from the dataset
3482 if (mTargetPackage == null && pmAgent != null) {
3483 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003484 mAncestralToken = mToken;
3485 writeRestoreTokens();
3486 }
3487
Christopher Tate1bb69062010-02-19 17:02:12 -08003488 // We must under all circumstances tell the Package Manager to
3489 // proceed with install notifications if it's waiting for us.
3490 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003491 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08003492 try {
3493 mPackageManagerBinder.finishPackageInstall(mPmToken);
3494 } catch (RemoteException e) { /* can't happen */ }
3495 }
3496
Christopher Tate73a3cb32010-12-13 18:27:26 -08003497 // Furthermore we need to reset the session timeout clock
3498 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3499 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
3500 TIMEOUT_RESTORE_INTERVAL);
3501
Christopher Tateb6787f22009-07-02 17:40:45 -07003502 // done; we can finally release the wakelock
3503 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07003504 }
3505 }
3506
Dan Egnorefe52642009-06-24 00:16:33 -07003507 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07003508 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
3509 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003510 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07003511 final String packageName = app.packageName;
3512
Joe Onorato8a9b2202010-02-26 18:56:32 -08003513 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003514
Christopher Tatec7b31e32009-06-10 15:49:30 -07003515 // !!! TODO: get the dirs from the transport
3516 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003517 File newStateName = new File(mStateDir, packageName + ".new");
3518 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003519
Dan Egnorbb9001c2009-07-27 12:20:13 -07003520 ParcelFileDescriptor backupData = null;
3521 ParcelFileDescriptor newState = null;
3522
Christopher Tate4a627c72011-04-01 14:43:32 -07003523 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003524 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07003525 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07003526 backupData = ParcelFileDescriptor.open(backupDataName,
3527 ParcelFileDescriptor.MODE_READ_WRITE |
3528 ParcelFileDescriptor.MODE_CREATE |
3529 ParcelFileDescriptor.MODE_TRUNCATE);
3530
Dan Egnor01445162009-09-21 17:04:05 -07003531 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003532 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003533 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003534 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07003535 }
3536
3537 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07003538 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07003539 backupData = ParcelFileDescriptor.open(backupDataName,
3540 ParcelFileDescriptor.MODE_READ_ONLY);
3541
Dan Egnorbb9001c2009-07-27 12:20:13 -07003542 newState = ParcelFileDescriptor.open(newStateName,
3543 ParcelFileDescriptor.MODE_READ_WRITE |
3544 ParcelFileDescriptor.MODE_CREATE |
3545 ParcelFileDescriptor.MODE_TRUNCATE);
3546
Christopher Tate44a27902010-01-27 17:15:49 -08003547 // Kick off the restore, checking for hung agents
3548 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
3549 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
3550 boolean success = waitUntilOperationComplete(token);
3551
3552 if (!success) {
3553 throw new RuntimeException("restore timeout");
3554 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07003555
3556 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07003557 //
3558 // !!! TODO: the restored data should be migrated on the server
3559 // side into the current dataset. In that case the new state file
3560 // we just created would reflect the data already extant in the
3561 // backend, so there'd be nothing more to do. Until that happens,
3562 // however, we need to make sure that we record the data to the
3563 // current backend dataset. (Yes, this means shipping the data over
3564 // the wire in both directions. That's bad, but consistency comes
3565 // first, then efficiency.) Once we introduce server-side data
3566 // migration to the newly-restored device's dataset, we will change
3567 // the following from a discard of the newly-written state to the
3568 // "correct" operation of renaming into the canonical state blob.
3569 newStateName.delete(); // TODO: remove; see above comment
3570 //newStateName.renameTo(savedStateName); // TODO: replace with this
3571
Dan Egnorbb9001c2009-07-27 12:20:13 -07003572 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003573 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003574 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003575 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003576 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07003577
Christopher Tate96733042009-07-20 14:49:13 -07003578 // If the agent fails restore, it might have put the app's data
3579 // into an incoherent state. For consistency we wipe its data
3580 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07003581 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07003582 } finally {
3583 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003584 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
3585 try { if (newState != null) newState.close(); } catch (IOException e) {}
3586 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07003587 synchronized (mCurrentOperations) {
3588 mCurrentOperations.delete(token);
3589 }
Chris Tate249345b2010-10-29 12:57:04 -07003590
3591 // If we know a priori that we'll need to perform a full post-restore backup
3592 // pass, clear the new state file data. This means we're discarding work that
3593 // was just done by the app's agent, but this way the agent doesn't need to
3594 // take any special action based on global device state.
3595 if (needFullBackup) {
3596 newStateName.delete();
3597 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07003598 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003599 }
3600 }
3601
Christopher Tate44a27902010-01-27 17:15:49 -08003602 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07003603 IBackupTransport mTransport;
3604 PackageInfo mPackage;
3605
Christopher Tate44a27902010-01-27 17:15:49 -08003606 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07003607 mTransport = transport;
3608 mPackage = packageInfo;
3609 }
3610
Christopher Tateee0e78a2009-07-02 11:17:03 -07003611 public void run() {
3612 try {
3613 // Clear the on-device backup state to ensure a full backup next time
3614 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
3615 File stateFile = new File(stateDir, mPackage.packageName);
3616 stateFile.delete();
3617
3618 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07003619 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07003620 mTransport.clearBackupData(mPackage);
3621 } catch (RemoteException e) {
3622 // can't happen; the transport is local
3623 } finally {
3624 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07003625 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07003626 mTransport.finishBackup();
3627 } catch (RemoteException e) {
3628 // can't happen; the transport is local
3629 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003630
3631 // Last but not least, release the cpu
3632 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07003633 }
3634 }
3635 }
3636
Christopher Tate44a27902010-01-27 17:15:49 -08003637 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003638 HashSet<String> mQueue;
3639
Christopher Tate44a27902010-01-27 17:15:49 -08003640 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003641 mQueue = transportNames;
3642 }
3643
Christopher Tate4cc86e12009-09-21 19:36:51 -07003644 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003645 try {
3646 for (String transportName : mQueue) {
3647 IBackupTransport transport = getTransport(transportName);
3648 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003649 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07003650 continue;
3651 }
3652
Joe Onorato8a9b2202010-02-26 18:56:32 -08003653 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003654 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07003655 long startRealtime = SystemClock.elapsedRealtime();
3656 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07003657
Christopher Tate4cc86e12009-09-21 19:36:51 -07003658 if (status == BackupConstants.TRANSPORT_OK) {
3659 status = transport.finishBackup();
3660 }
3661
3662 // Okay, the wipe really happened. Clean up our local bookkeeping.
3663 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003664 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07003665 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003666 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07003667 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003668 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003669 synchronized (mQueueLock) {
3670 recordInitPendingLocked(false, transportName);
3671 }
Dan Egnor726247c2009-09-29 19:12:31 -07003672 } else {
3673 // If this didn't work, requeue this one and try again
3674 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08003675 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003676 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07003677 synchronized (mQueueLock) {
3678 recordInitPendingLocked(true, transportName);
3679 }
3680 // do this via another alarm to make sure of the wakelock states
3681 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003682 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07003683 + transportName + " resched in " + delay);
3684 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
3685 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003686 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07003687 }
3688 } catch (RemoteException e) {
3689 // can't happen; the transports are local
3690 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003691 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003692 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08003693 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07003694 mWakelock.release();
3695 }
3696 }
3697 }
3698
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003699 private void dataChangedImpl(String packageName) {
3700 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
3701 dataChangedImpl(packageName, targets);
3702 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003703
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003704 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07003705 // Record that we need a backup pass for the caller. Since multiple callers
3706 // may share a uid, we need to note all candidates within that uid and schedule
3707 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003708 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003709
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003710 if (targets == null) {
3711 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
3712 + " uid=" + Binder.getCallingUid());
3713 return;
3714 }
3715
3716 synchronized (mQueueLock) {
3717 // Note that this client has made data changes that need to be backed up
3718 for (ApplicationInfo app : targets) {
3719 // validate the caller-supplied package name against the known set of
3720 // packages associated with this uid
3721 if (app.packageName.equals(packageName)) {
3722 // Add the caller to the set of pending backups. If there is
3723 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07003724 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08003725 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003726 // Journal this request in case of crash. The put()
3727 // operation returned null when this package was not already
3728 // in the set; we want to avoid touching the disk redundantly.
3729 writeToJournalLocked(packageName);
3730
3731 if (DEBUG) {
3732 int numKeys = mPendingBackups.size();
3733 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
3734 for (BackupRequest b : mPendingBackups.values()) {
3735 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
3736 }
3737 }
3738 }
3739 }
3740 }
3741 }
3742 }
3743
3744 // Note: packageName is currently unused, but may be in the future
3745 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07003746 // If the caller does not hold the BACKUP permission, it can only request a
3747 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07003748 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07003749 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003750 synchronized (mBackupParticipants) {
3751 return mBackupParticipants.get(Binder.getCallingUid());
3752 }
3753 }
3754
3755 // a caller with full permission can ask to back up any participating app
3756 // !!! TODO: allow backup of ANY app?
3757 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
3758 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07003759 int N = mBackupParticipants.size();
3760 for (int i = 0; i < N; i++) {
3761 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
3762 if (s != null) {
3763 targets.addAll(s);
3764 }
3765 }
3766 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003767 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07003768 }
Christopher Tate46758122009-05-06 11:22:00 -07003769
Christopher Tatecde87f42009-06-12 12:55:53 -07003770 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07003771 RandomAccessFile out = null;
3772 try {
3773 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
3774 out = new RandomAccessFile(mJournal, "rws");
3775 out.seek(out.length());
3776 out.writeUTF(str);
3777 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003778 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07003779 mJournal = null;
3780 } finally {
3781 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07003782 }
3783 }
3784
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003785 // ----- IBackupManager binder interface -----
3786
3787 public void dataChanged(final String packageName) {
3788 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
3789 if (targets == null) {
3790 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
3791 + " uid=" + Binder.getCallingUid());
3792 return;
3793 }
3794
3795 mBackupHandler.post(new Runnable() {
3796 public void run() {
3797 dataChangedImpl(packageName, targets);
3798 }
3799 });
3800 }
3801
Christopher Tateee0e78a2009-07-02 11:17:03 -07003802 // Clear the given package's backup data from the current transport
3803 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003804 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07003805 PackageInfo info;
3806 try {
3807 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
3808 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003810 return;
3811 }
3812
3813 // If the caller does not hold the BACKUP permission, it can only request a
3814 // wipe of its own backed-up data.
3815 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07003816 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07003817 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
3818 apps = mBackupParticipants.get(Binder.getCallingUid());
3819 } else {
3820 // a caller with full permission can ask to back up any participating app
3821 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08003822 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003823 apps = new HashSet<ApplicationInfo>();
3824 int N = mBackupParticipants.size();
3825 for (int i = 0; i < N; i++) {
3826 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
3827 if (s != null) {
3828 apps.addAll(s);
3829 }
3830 }
3831 }
3832
3833 // now find the given package in the set of candidate apps
3834 for (ApplicationInfo app : apps) {
3835 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003836 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003837 // found it; fire off the clear request
3838 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07003839 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07003840 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07003841 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
3842 new ClearParams(getTransport(mCurrentTransport), info));
3843 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07003844 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07003845 }
3846 break;
3847 }
3848 }
3849 }
3850
Christopher Tateace7f092009-06-15 18:07:25 -07003851 // Run a backup pass immediately for any applications that have declared
3852 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07003853 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04003854 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07003855
Joe Onorato8a9b2202010-02-26 18:56:32 -08003856 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07003857 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07003858 // Because the alarms we are using can jitter, and we want an *immediate*
3859 // backup pass to happen, we restart the timer beginning with "next time,"
3860 // then manually fire the backup trigger intent ourselves.
3861 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07003862 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07003863 mRunBackupIntent.send();
3864 } catch (PendingIntent.CanceledException e) {
3865 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08003866 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07003867 }
Christopher Tate46758122009-05-06 11:22:00 -07003868 }
3869 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003870
Christopher Tate4a627c72011-04-01 14:43:32 -07003871 // Run a *full* backup pass for the given package, writing the resulting data stream
3872 // to the supplied file descriptor. This method is synchronous and does not return
3873 // to the caller until the backup has been completed.
3874 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
3875 boolean doAllApps, String[] pkgList) {
3876 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
3877
3878 // Validate
3879 if (!doAllApps) {
3880 if (!includeShared) {
3881 // If we're backing up shared data (sdcard or equivalent), then we can run
3882 // without any supplied app names. Otherwise, we'd be doing no work, so
3883 // report the error.
3884 if (pkgList == null || pkgList.length == 0) {
3885 throw new IllegalArgumentException(
3886 "Backup requested but neither shared nor any apps named");
3887 }
3888 }
3889 }
3890
3891 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
3892 + " shared=" + includeShared + " all=" + doAllApps
3893 + " pkgs=" + pkgList);
3894
3895 long oldId = Binder.clearCallingIdentity();
3896 try {
3897 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
3898 doAllApps, pkgList);
3899 final int token = generateToken();
3900 synchronized (mFullConfirmations) {
3901 mFullConfirmations.put(token, params);
3902 }
3903
Christopher Tate75a99702011-05-18 16:28:19 -07003904 // start up the confirmation UI
3905 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
3906 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
3907 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07003908 mFullConfirmations.delete(token);
3909 return;
3910 }
Christopher Tate75a99702011-05-18 16:28:19 -07003911
3912 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07003913 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3914
3915 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07003916 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07003917
3918 // wait for the backup to be performed
3919 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
3920 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07003921 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07003922 try {
3923 fd.close();
3924 } catch (IOException e) {
3925 // just eat it
3926 }
Christopher Tate75a99702011-05-18 16:28:19 -07003927 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07003928 }
Christopher Tate75a99702011-05-18 16:28:19 -07003929 if (DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
3930 }
3931
3932 public void fullRestore(ParcelFileDescriptor fd) {
3933 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
3934 Slog.i(TAG, "Beginning full restore...");
3935
3936 long oldId = Binder.clearCallingIdentity();
3937
3938 try {
3939 FullRestoreParams params = new FullRestoreParams(fd);
3940 final int token = generateToken();
3941 synchronized (mFullConfirmations) {
3942 mFullConfirmations.put(token, params);
3943 }
3944
3945 // start up the confirmation UI
3946 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
3947 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
3948 Slog.e(TAG, "Unable to launch full restore confirmation");
3949 mFullConfirmations.delete(token);
3950 return;
3951 }
3952
3953 // make sure the screen is lit for the user interaction
3954 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3955
3956 // start the confirmation countdown
3957 startConfirmationTimeout(token, params);
3958
3959 // wait for the restore to be performed
3960 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
3961 waitForCompletion(params);
3962 } finally {
3963 try {
3964 fd.close();
3965 } catch (IOException e) {
3966 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
3967 }
3968 Binder.restoreCallingIdentity(oldId);
3969 Slog.i(TAG, "Full restore completed");
3970 }
3971 }
3972
3973 boolean startConfirmationUi(int token, String action) {
3974 try {
3975 Intent confIntent = new Intent(action);
3976 confIntent.setClassName("com.android.backupconfirm",
3977 "com.android.backupconfirm.BackupRestoreConfirmation");
3978 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
3979 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3980 mContext.startActivity(confIntent);
3981 } catch (ActivityNotFoundException e) {
3982 return false;
3983 }
3984 return true;
3985 }
3986
3987 void startConfirmationTimeout(int token, FullParams params) {
3988 if (DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
3989 + TIMEOUT_FULL_CONFIRMATION + " millis");
3990 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
3991 token, 0, params);
3992 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07003993 }
3994
3995 void waitForCompletion(FullParams params) {
3996 synchronized (params.latch) {
3997 while (params.latch.get() == false) {
3998 try {
3999 params.latch.wait();
4000 } catch (InterruptedException e) { /* never interrupted */ }
4001 }
4002 }
4003 }
4004
4005 void signalFullBackupRestoreCompletion(FullParams params) {
4006 synchronized (params.latch) {
4007 params.latch.set(true);
4008 params.latch.notifyAll();
4009 }
4010 }
4011
4012 // Confirm that the previously-requested full backup/restore operation can proceed. This
4013 // is used to require a user-facing disclosure about the operation.
4014 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
4015 IFullBackupRestoreObserver observer) {
4016 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
4017 + " allow=" + allow);
4018
4019 // TODO: possibly require not just this signature-only permission, but even
4020 // require that the specific designated confirmation-UI app uid is the caller?
4021 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
4022
4023 long oldId = Binder.clearCallingIdentity();
4024 try {
4025
4026 FullParams params;
4027 synchronized (mFullConfirmations) {
4028 params = mFullConfirmations.get(token);
4029 if (params != null) {
4030 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
4031 mFullConfirmations.delete(token);
4032
4033 if (allow) {
4034 params.observer = observer;
4035 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07004036 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07004037 : MSG_RUN_FULL_RESTORE;
4038
Christopher Tate75a99702011-05-18 16:28:19 -07004039 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07004040 mWakelock.acquire();
4041 Message msg = mBackupHandler.obtainMessage(verb, params);
4042 mBackupHandler.sendMessage(msg);
4043 } else {
4044 Slog.w(TAG, "User rejected full backup/restore operation");
4045 // indicate completion without having actually transferred any data
4046 signalFullBackupRestoreCompletion(params);
4047 }
4048 } else {
4049 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
4050 }
4051 }
4052 } finally {
4053 Binder.restoreCallingIdentity(oldId);
4054 }
4055 }
4056
Christopher Tate8031a3d2009-07-06 16:36:05 -07004057 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07004058 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004059 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4a627c72011-04-01 14:43:32 -07004060 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004061
Joe Onorato8a9b2202010-02-26 18:56:32 -08004062 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004063
Christopher Tate6ef58a12009-06-29 14:56:28 -07004064 boolean wasEnabled = mEnabled;
4065 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07004066 Settings.Secure.putInt(mContext.getContentResolver(),
4067 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07004068 mEnabled = enable;
4069 }
4070
Christopher Tate49401dd2009-07-01 12:34:29 -07004071 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004072 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07004073 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07004074 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07004075 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07004076 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004077 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07004078
Christopher Tateb6787f22009-07-02 17:40:45 -07004079 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07004080
4081 // This also constitutes an opt-out, so we wipe any data for
4082 // this device from the backend. We start that process with
4083 // an alarm in order to guarantee wakelock states.
4084 if (wasEnabled && mProvisioned) {
4085 // NOTE: we currently flush every registered transport, not just
4086 // the currently-active one.
4087 HashSet<String> allTransports;
4088 synchronized (mTransports) {
4089 allTransports = new HashSet<String>(mTransports.keySet());
4090 }
4091 // build the set of transports for which we are posting an init
4092 for (String transport : allTransports) {
4093 recordInitPendingLocked(true, transport);
4094 }
4095 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
4096 mRunInitIntent);
4097 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004098 }
4099 }
Christopher Tate49401dd2009-07-01 12:34:29 -07004100 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07004101
Christopher Tatecce9da52010-02-03 15:11:15 -08004102 // Enable/disable automatic restore of app data at install time
4103 public void setAutoRestore(boolean doAutoRestore) {
4104 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4105 "setBackupEnabled");
4106
Joe Onorato8a9b2202010-02-26 18:56:32 -08004107 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08004108
4109 synchronized (this) {
4110 Settings.Secure.putInt(mContext.getContentResolver(),
4111 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
4112 mAutoRestore = doAutoRestore;
4113 }
4114 }
4115
Christopher Tate8031a3d2009-07-06 16:36:05 -07004116 // Mark the backup service as having been provisioned
4117 public void setBackupProvisioned(boolean available) {
4118 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4119 "setBackupProvisioned");
4120
4121 boolean wasProvisioned = mProvisioned;
4122 synchronized (this) {
4123 Settings.Secure.putInt(mContext.getContentResolver(),
4124 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
4125 mProvisioned = available;
4126 }
4127
4128 synchronized (mQueueLock) {
4129 if (available && !wasProvisioned && mEnabled) {
4130 // we're now good to go, so start the backup alarms
4131 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
4132 } else if (!available) {
4133 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08004134 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07004135 mAlarmManager.cancel(mRunBackupIntent);
4136 }
4137 }
4138 }
4139
4140 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07004141 // We used to use setInexactRepeating(), but that may be linked to
4142 // backups running at :00 more often than not, creating load spikes.
4143 // Schedule at an exact time for now, and also add a bit of "fuzz".
4144
4145 Random random = new Random();
4146 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
4147 random.nextInt(FUZZ_MILLIS);
4148 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
4149 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07004150 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07004151 }
4152
Christopher Tate6ef58a12009-06-29 14:56:28 -07004153 // Report whether the backup mechanism is currently enabled
4154 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04004155 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07004156 return mEnabled; // no need to synchronize just to read it
4157 }
4158
Christopher Tate91717492009-06-26 21:07:13 -07004159 // Report the name of the currently active transport
4160 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04004161 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07004162 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08004163 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07004164 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07004165 }
4166
Christopher Tate91717492009-06-26 21:07:13 -07004167 // Report all known, available backup transports
4168 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07004169 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07004170
Christopher Tate91717492009-06-26 21:07:13 -07004171 String[] list = null;
4172 ArrayList<String> known = new ArrayList<String>();
4173 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
4174 if (entry.getValue() != null) {
4175 known.add(entry.getKey());
4176 }
4177 }
4178
4179 if (known.size() > 0) {
4180 list = new String[known.size()];
4181 known.toArray(list);
4182 }
4183 return list;
4184 }
4185
4186 // Select which transport to use for the next backup operation. If the given
4187 // name is not one of the available transports, no action is taken and the method
4188 // returns null.
4189 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04004190 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07004191
4192 synchronized (mTransports) {
4193 String prevTransport = null;
4194 if (mTransports.get(transport) != null) {
4195 prevTransport = mCurrentTransport;
4196 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07004197 Settings.Secure.putString(mContext.getContentResolver(),
4198 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004199 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07004200 + " returning " + prevTransport);
4201 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004202 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07004203 }
4204 return prevTransport;
4205 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004206 }
4207
Christopher Tatef5e1c292010-12-08 18:40:26 -08004208 // Supply the configuration Intent for the given transport. If the name is not one
4209 // of the available transports, or if the transport does not supply any configuration
4210 // UI, the method returns null.
4211 public Intent getConfigurationIntent(String transportName) {
4212 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4213 "getConfigurationIntent");
4214
4215 synchronized (mTransports) {
4216 final IBackupTransport transport = mTransports.get(transportName);
4217 if (transport != null) {
4218 try {
4219 final Intent intent = transport.configurationIntent();
4220 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
4221 + intent);
4222 return intent;
4223 } catch (RemoteException e) {
4224 /* fall through to return null */
4225 }
4226 }
4227 }
4228
4229 return null;
4230 }
4231
4232 // Supply the configuration summary string for the given transport. If the name is
4233 // not one of the available transports, or if the transport does not supply any
4234 // summary / destination string, the method can return null.
4235 //
4236 // This string is used VERBATIM as the summary text of the relevant Settings item!
4237 public String getDestinationString(String transportName) {
4238 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4239 "getConfigurationIntent");
4240
4241 synchronized (mTransports) {
4242 final IBackupTransport transport = mTransports.get(transportName);
4243 if (transport != null) {
4244 try {
4245 final String text = transport.currentDestinationString();
4246 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
4247 return text;
4248 } catch (RemoteException e) {
4249 /* fall through to return null */
4250 }
4251 }
4252 }
4253
4254 return null;
4255 }
4256
Christopher Tate043dadc2009-06-02 16:11:00 -07004257 // Callback: a requested backup agent has been instantiated. This should only
4258 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004259 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07004260 synchronized(mAgentConnectLock) {
4261 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004262 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07004263 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
4264 mConnectedAgent = agent;
4265 mConnecting = false;
4266 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004267 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004268 + " claiming agent connected");
4269 }
4270 mAgentConnectLock.notifyAll();
4271 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004272 }
4273
4274 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
4275 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07004276 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004277 public void agentDisconnected(String packageName) {
4278 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07004279 synchronized(mAgentConnectLock) {
4280 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
4281 mConnectedAgent = null;
4282 mConnecting = false;
4283 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004284 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004285 + " claiming agent disconnected");
4286 }
4287 mAgentConnectLock.notifyAll();
4288 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004289 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004290
Christopher Tate1bb69062010-02-19 17:02:12 -08004291 // An application being installed will need a restore pass, then the Package Manager
4292 // will need to be told when the restore is finished.
4293 public void restoreAtInstall(String packageName, int token) {
4294 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004295 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08004296 + " attemping install-time restore");
4297 return;
4298 }
4299
4300 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004301 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08004302 + " token=" + Integer.toHexString(token));
4303
Christopher Tatef0872722010-02-25 15:22:48 -08004304 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08004305 // okay, we're going to attempt a restore of this package from this restore set.
4306 // The eventual message back into the Package Manager to run the post-install
4307 // steps for 'token' will be issued from the restore handling code.
4308
4309 // We can use a synthetic PackageInfo here because:
4310 // 1. We know it's valid, since the Package Manager supplied the name
4311 // 2. Only the packageName field will be used by the restore code
4312 PackageInfo pkg = new PackageInfo();
4313 pkg.packageName = packageName;
4314
4315 mWakelock.acquire();
4316 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4317 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07004318 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08004319 mBackupHandler.sendMessage(msg);
4320 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08004321 // Auto-restore disabled or no way to attempt a restore; just tell the Package
4322 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004323 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08004324 try {
4325 mPackageManagerBinder.finishPackageInstall(token);
4326 } catch (RemoteException e) { /* can't happen */ }
4327 }
4328 }
4329
Christopher Tate8c850b72009-06-07 19:33:20 -07004330 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08004331 public IRestoreSession beginRestoreSession(String packageName, String transport) {
4332 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
4333 + " transport=" + transport);
4334
4335 boolean needPermission = true;
4336 if (transport == null) {
4337 transport = mCurrentTransport;
4338
4339 if (packageName != null) {
4340 PackageInfo app = null;
4341 try {
4342 app = mPackageManager.getPackageInfo(packageName, 0);
4343 } catch (NameNotFoundException nnf) {
4344 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
4345 throw new IllegalArgumentException("Package " + packageName + " not found");
4346 }
4347
4348 if (app.applicationInfo.uid == Binder.getCallingUid()) {
4349 // So: using the current active transport, and the caller has asked
4350 // that its own package will be restored. In this narrow use case
4351 // we do not require the caller to hold the permission.
4352 needPermission = false;
4353 }
4354 }
4355 }
4356
4357 if (needPermission) {
4358 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4359 "beginRestoreSession");
4360 } else {
4361 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
4362 }
Christopher Tatef68eb502009-06-16 11:02:01 -07004363
4364 synchronized(this) {
4365 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004366 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07004367 return null;
4368 }
Chris Tate44ab8452010-11-16 15:10:49 -08004369 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08004370 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07004371 }
4372 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07004373 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004374
Christopher Tate73a3cb32010-12-13 18:27:26 -08004375 void clearRestoreSession(ActiveRestoreSession currentSession) {
4376 synchronized(this) {
4377 if (currentSession != mActiveRestoreSession) {
4378 Slog.e(TAG, "ending non-current restore session");
4379 } else {
4380 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
4381 mActiveRestoreSession = null;
4382 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4383 }
4384 }
4385 }
4386
Christopher Tate44a27902010-01-27 17:15:49 -08004387 // Note that a currently-active backup agent has notified us that it has
4388 // completed the given outstanding asynchronous backup/restore operation.
4389 public void opComplete(int token) {
4390 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004391 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08004392 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
4393 mCurrentOpLock.notifyAll();
4394 }
4395 }
4396
Christopher Tate9b3905c2009-06-08 15:24:01 -07004397 // ----- Restore session -----
4398
Christopher Tate80202c82010-01-25 19:37:47 -08004399 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07004400 private static final String TAG = "RestoreSession";
4401
Chris Tate44ab8452010-11-16 15:10:49 -08004402 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004403 private IBackupTransport mRestoreTransport = null;
4404 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08004405 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004406
Chris Tate44ab8452010-11-16 15:10:49 -08004407 ActiveRestoreSession(String packageName, String transport) {
4408 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07004409 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07004410 }
4411
4412 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07004413 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04004414 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004415 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004416 if (observer == null) {
4417 throw new IllegalArgumentException("Observer must not be null");
4418 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004419
Christopher Tate73a3cb32010-12-13 18:27:26 -08004420 if (mEnded) {
4421 throw new IllegalStateException("Restore session already ended");
4422 }
4423
Christopher Tate1bb69062010-02-19 17:02:12 -08004424 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07004425 try {
Christopher Tate43383042009-07-13 15:17:13 -07004426 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004427 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004428 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07004429 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07004430 // spin off the transport request to our service thread
4431 mWakelock.acquire();
4432 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
4433 new RestoreGetSetsParams(mRestoreTransport, this, observer));
4434 mBackupHandler.sendMessage(msg);
4435 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07004436 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004437 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07004438 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08004439 } finally {
4440 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07004441 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07004442 }
4443
Christopher Tate84725812010-02-04 15:52:40 -08004444 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07004445 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4446 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004447
Chris Tate44ab8452010-11-16 15:10:49 -08004448 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07004449 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004450
Christopher Tate73a3cb32010-12-13 18:27:26 -08004451 if (mEnded) {
4452 throw new IllegalStateException("Restore session already ended");
4453 }
4454
Dan Egnor0084da52009-07-29 12:57:16 -07004455 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08004456 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4457 return -1;
4458 }
4459
4460 if (mPackageName != null) {
4461 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07004462 return -1;
4463 }
4464
Christopher Tate21ab6a52009-09-24 18:01:46 -07004465 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004466 for (int i = 0; i < mRestoreSets.length; i++) {
4467 if (token == mRestoreSets[i].token) {
4468 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07004469 mWakelock.acquire();
4470 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004471 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07004472 mBackupHandler.sendMessage(msg);
4473 Binder.restoreCallingIdentity(oldId);
4474 return 0;
4475 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004476 }
4477 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07004478
Joe Onorato8a9b2202010-02-26 18:56:32 -08004479 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07004480 return -1;
4481 }
4482
Christopher Tate284f1bb2011-07-07 14:31:18 -07004483 public synchronized int restoreSome(long token, IRestoreObserver observer,
4484 String[] packages) {
4485 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4486 "performRestore");
4487
4488 if (DEBUG) {
4489 StringBuilder b = new StringBuilder(128);
4490 b.append("restoreSome token=");
4491 b.append(Long.toHexString(token));
4492 b.append(" observer=");
4493 b.append(observer.toString());
4494 b.append(" packages=");
4495 if (packages == null) {
4496 b.append("null");
4497 } else {
4498 b.append('{');
4499 boolean first = true;
4500 for (String s : packages) {
4501 if (!first) {
4502 b.append(", ");
4503 } else first = false;
4504 b.append(s);
4505 }
4506 b.append('}');
4507 }
4508 Slog.d(TAG, b.toString());
4509 }
4510
4511 if (mEnded) {
4512 throw new IllegalStateException("Restore session already ended");
4513 }
4514
4515 if (mRestoreTransport == null || mRestoreSets == null) {
4516 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4517 return -1;
4518 }
4519
4520 if (mPackageName != null) {
4521 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
4522 return -1;
4523 }
4524
4525 synchronized (mQueueLock) {
4526 for (int i = 0; i < mRestoreSets.length; i++) {
4527 if (token == mRestoreSets[i].token) {
4528 long oldId = Binder.clearCallingIdentity();
4529 mWakelock.acquire();
4530 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4531 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
4532 packages, true);
4533 mBackupHandler.sendMessage(msg);
4534 Binder.restoreCallingIdentity(oldId);
4535 return 0;
4536 }
4537 }
4538 }
4539
4540 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
4541 return -1;
4542 }
4543
Christopher Tate84725812010-02-04 15:52:40 -08004544 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004545 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08004546
Christopher Tate73a3cb32010-12-13 18:27:26 -08004547 if (mEnded) {
4548 throw new IllegalStateException("Restore session already ended");
4549 }
4550
Chris Tate44ab8452010-11-16 15:10:49 -08004551 if (mPackageName != null) {
4552 if (! mPackageName.equals(packageName)) {
4553 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
4554 + " on session for package " + mPackageName);
4555 return -1;
4556 }
4557 }
4558
Christopher Tate84725812010-02-04 15:52:40 -08004559 PackageInfo app = null;
4560 try {
4561 app = mPackageManager.getPackageInfo(packageName, 0);
4562 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004563 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08004564 return -1;
4565 }
4566
4567 // If the caller is not privileged and is not coming from the target
4568 // app's uid, throw a permission exception back to the caller.
4569 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
4570 Binder.getCallingPid(), Binder.getCallingUid());
4571 if ((perm == PackageManager.PERMISSION_DENIED) &&
4572 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004573 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08004574 + " or calling uid=" + Binder.getCallingUid());
4575 throw new SecurityException("No permission to restore other packages");
4576 }
4577
Christopher Tate7d411a32010-02-26 11:27:08 -08004578 // If the package has no backup agent, we obviously cannot proceed
4579 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004580 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08004581 return -1;
4582 }
4583
Christopher Tate84725812010-02-04 15:52:40 -08004584 // So far so good; we're allowed to try to restore this package. Now
4585 // check whether there is data for it in the current dataset, falling back
4586 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08004587 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08004588
4589 // If we didn't come up with a place to look -- no ancestral dataset and
4590 // the app has never been backed up from this device -- there's nothing
4591 // to do but return failure.
4592 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08004593 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08004594 return -1;
4595 }
4596
4597 // Ready to go: enqueue the restore request and claim success
4598 long oldId = Binder.clearCallingIdentity();
4599 mWakelock.acquire();
4600 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004601 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08004602 mBackupHandler.sendMessage(msg);
4603 Binder.restoreCallingIdentity(oldId);
4604 return 0;
4605 }
4606
Christopher Tate73a3cb32010-12-13 18:27:26 -08004607 // Posted to the handler to tear down a restore session in a cleanly synchronized way
4608 class EndRestoreRunnable implements Runnable {
4609 BackupManagerService mBackupManager;
4610 ActiveRestoreSession mSession;
4611
4612 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
4613 mBackupManager = manager;
4614 mSession = session;
4615 }
4616
4617 public void run() {
4618 // clean up the session's bookkeeping
4619 synchronized (mSession) {
4620 try {
4621 if (mSession.mRestoreTransport != null) {
4622 mSession.mRestoreTransport.finishRestore();
4623 }
4624 } catch (Exception e) {
4625 Slog.e(TAG, "Error in finishRestore", e);
4626 } finally {
4627 mSession.mRestoreTransport = null;
4628 mSession.mEnded = true;
4629 }
4630 }
4631
4632 // clean up the BackupManagerService side of the bookkeeping
4633 // and cancel any pending timeout message
4634 mBackupManager.clearRestoreSession(mSession);
4635 }
4636 }
4637
Dan Egnor0084da52009-07-29 12:57:16 -07004638 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004639 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004640
Christopher Tate73a3cb32010-12-13 18:27:26 -08004641 if (mEnded) {
4642 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07004643 }
4644
Christopher Tate73a3cb32010-12-13 18:27:26 -08004645 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07004646 }
4647 }
4648
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004649 @Override
4650 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004651 long identityToken = Binder.clearCallingIdentity();
4652 try {
4653 dumpInternal(pw);
4654 } finally {
4655 Binder.restoreCallingIdentity(identityToken);
4656 }
4657 }
4658
4659 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004660 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004661 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07004662 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08004663 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08004664 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07004665 pw.println("Last backup pass: " + mLastBackupPass
4666 + " (now = " + System.currentTimeMillis() + ')');
4667 pw.println(" next scheduled: " + mNextBackupPass);
4668
Christopher Tate91717492009-06-26 21:07:13 -07004669 pw.println("Available transports:");
4670 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004671 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
4672 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004673 IBackupTransport transport = getTransport(t);
4674 File dir = new File(mBaseStateDir, transport.transportDirName());
4675 pw.println(" destination: " + transport.currentDestinationString());
4676 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07004677 for (File f : dir.listFiles()) {
4678 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
4679 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004680 } catch (Exception e) {
4681 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004682 pw.println(" Error: " + e);
4683 }
Christopher Tate91717492009-06-26 21:07:13 -07004684 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004685
4686 pw.println("Pending init: " + mPendingInits.size());
4687 for (String s : mPendingInits) {
4688 pw.println(" " + s);
4689 }
4690
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004691 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07004692 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004693 for (int i=0; i<N; i++) {
4694 int uid = mBackupParticipants.keyAt(i);
4695 pw.print(" uid: ");
4696 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004697 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
4698 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07004699 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004700 }
4701 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004702
Christopher Tateb49ceb32010-02-08 16:22:24 -08004703 pw.println("Ancestral packages: "
4704 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07004705 if (mAncestralPackages != null) {
4706 for (String pkg : mAncestralPackages) {
4707 pw.println(" " + pkg);
4708 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08004709 }
4710
Christopher Tate73e02522009-07-15 14:18:26 -07004711 pw.println("Ever backed up: " + mEverStoredApps.size());
4712 for (String pkg : mEverStoredApps) {
4713 pw.println(" " + pkg);
4714 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004715
4716 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07004717 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07004718 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07004719 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004720 }
4721 }
Christopher Tate487529a2009-04-29 14:03:25 -07004722}