blob: 786f2fad681d603b4113352d6f7207873b691a87 [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 Tatecde87f42009-06-12 12:55:53 -070079import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070080import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070081import java.io.FileDescriptor;
Christopher Tate75a99702011-05-18 16:28:19 -070082import java.io.FileInputStream;
Christopher Tate1168baa2010-02-17 13:03:40 -080083import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070084import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070085import java.io.IOException;
Christopher Tate75a99702011-05-18 16:28:19 -070086import java.io.InputStream;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070087import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070088import java.io.RandomAccessFile;
Christopher Tate75a99702011-05-18 16:28:19 -070089import java.text.SimpleDateFormat;
Joe Onorato8ad02812009-05-13 01:41:44 -040090import java.util.ArrayList;
Christopher Tate75a99702011-05-18 16:28:19 -070091import java.util.Date;
Joe Onorato8ad02812009-05-13 01:41:44 -040092import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070093import java.util.HashSet;
94import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070095import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070096import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080097import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -070098import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate487529a2009-04-29 14:03:25 -070099
100class BackupManagerService extends IBackupManager.Stub {
101 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -0700102 private static final boolean DEBUG = true;
103
104 // Name and current contents version of the full-backup manifest file
105 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
106 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tateaa088442009-06-16 18:25:46 -0700107
Christopher Tate49401dd2009-07-01 12:34:29 -0700108 // How often we perform a backup pass. Privileged external callers can
109 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700110 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700111
Dan Egnorc1c49c02009-10-30 17:35:39 -0700112 // Random variation in backup scheduling time to avoid server load spikes
113 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
114
Christopher Tate8031a3d2009-07-06 16:36:05 -0700115 // The amount of time between the initial provisioning of the device and
116 // the first backup pass.
117 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
118
Christopher Tate45281862010-03-05 15:46:30 -0800119 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
120 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
121 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700122 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700123 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700124 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700125 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700126 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700127 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
128 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800129 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700130 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
131 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700132
133 // Timeout interval for deciding that a bind or clear-data has taken too long
134 static final long TIMEOUT_INTERVAL = 10 * 1000;
135
Christopher Tate44a27902010-01-27 17:15:49 -0800136 // Timeout intervals for agent backup & restore operations
137 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700138 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tateb0628bf2011-06-02 15:08:13 -0700139 static final long TIMEOUT_SHARED_BACKUP_INTERVAL = 30 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800140 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
141
Christopher Tate4a627c72011-04-01 14:43:32 -0700142 // User confirmation timeout for a full backup/restore operation
143 static final long TIMEOUT_FULL_CONFIRMATION = 30 * 1000;
144
Christopher Tate487529a2009-04-29 14:03:25 -0700145 private Context mContext;
146 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800147 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700148 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700149 private PowerManager mPowerManager;
150 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800151 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700152
Christopher Tate73e02522009-07-15 14:18:26 -0700153 boolean mEnabled; // access to this is synchronized on 'this'
154 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800155 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700156 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800157 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
158 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700159 PendingIntent mRunBackupIntent, mRunInitIntent;
160 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700161 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700162 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700163 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700164 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700165 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700166 public ApplicationInfo appInfo;
Christopher Tateaa088442009-06-16 18:25:46 -0700167
Christopher Tate4a627c72011-04-01 14:43:32 -0700168 BackupRequest(ApplicationInfo app) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700169 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700170 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700171
172 public String toString() {
Christopher Tate4a627c72011-04-01 14:43:32 -0700173 return "BackupRequest{app=" + appInfo + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700174 }
Christopher Tate46758122009-05-06 11:22:00 -0700175 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800176 // Backups that we haven't started yet. Keys are package names.
177 HashMap<String,BackupRequest> mPendingBackups
178 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700179
180 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700181 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700182
183 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700184 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700185
Christopher Tate043dadc2009-06-02 16:11:00 -0700186 // The thread performing the sequence of queued backups binds to each app's agent
187 // in succession. Bind notifications are asynchronously delivered through the
188 // Activity Manager; use this lock object to signal when a requested binding has
189 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700190 final Object mAgentConnectLock = new Object();
191 IBackupAgent mConnectedAgent;
192 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700193 volatile long mLastBackupPass;
194 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700195
Christopher Tate55f931a2009-09-29 17:17:34 -0700196 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700197 final Object mClearDataLock = new Object();
198 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700199
Christopher Tate91717492009-06-26 21:07:13 -0700200 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700201 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700202 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700203 String mCurrentTransport;
204 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800205 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700206
Christopher Tate2d449afe2010-03-29 19:14:24 -0700207 class RestoreGetSetsParams {
208 public IBackupTransport transport;
209 public ActiveRestoreSession session;
210 public IRestoreObserver observer;
211
212 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
213 IRestoreObserver _observer) {
214 transport = _transport;
215 session = _session;
216 observer = _observer;
217 }
218 }
219
Christopher Tate73e02522009-07-15 14:18:26 -0700220 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700221 public IBackupTransport transport;
222 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700223 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800224 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800225 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700226 public boolean needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700227 public String[] filterSet;
Christopher Tate84725812010-02-04 15:52:40 -0800228
229 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700230 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800231 transport = _transport;
232 observer = _obs;
233 token = _token;
234 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800235 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700236 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700237 filterSet = null;
Christopher Tate84725812010-02-04 15:52:40 -0800238 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700239
Chris Tate249345b2010-10-29 12:57:04 -0700240 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
241 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700242 transport = _transport;
243 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700244 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800245 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800246 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700247 needFullBackup = _needFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -0700248 filterSet = null;
249 }
250
251 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
252 String[] _filterSet, boolean _needFullBackup) {
253 transport = _transport;
254 observer = _obs;
255 token = _token;
256 pkgInfo = null;
257 pmToken = 0;
258 needFullBackup = _needFullBackup;
259 filterSet = _filterSet;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700260 }
261 }
262
Christopher Tate73e02522009-07-15 14:18:26 -0700263 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700264 public IBackupTransport transport;
265 public PackageInfo packageInfo;
266
267 ClearParams(IBackupTransport _transport, PackageInfo _info) {
268 transport = _transport;
269 packageInfo = _info;
270 }
271 }
272
Christopher Tate4a627c72011-04-01 14:43:32 -0700273 class FullParams {
274 public ParcelFileDescriptor fd;
275 public final AtomicBoolean latch;
276 public IFullBackupRestoreObserver observer;
277
278 FullParams() {
279 latch = new AtomicBoolean(false);
280 }
281 }
282
283 class FullBackupParams extends FullParams {
284 public boolean includeApks;
285 public boolean includeShared;
286 public boolean allApps;
287 public String[] packages;
288
289 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
290 boolean doAllApps, String[] pkgList) {
291 fd = output;
292 includeApks = saveApks;
293 includeShared = saveShared;
294 allApps = doAllApps;
295 packages = pkgList;
296 }
297 }
298
299 class FullRestoreParams extends FullParams {
300 FullRestoreParams(ParcelFileDescriptor input) {
301 fd = input;
302 }
303 }
304
Christopher Tate44a27902010-01-27 17:15:49 -0800305 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
306 // token is the index of the entry in the pending-operations list.
307 static final int OP_PENDING = 0;
308 static final int OP_ACKNOWLEDGED = 1;
309 static final int OP_TIMEOUT = -1;
310
311 final SparseIntArray mCurrentOperations = new SparseIntArray();
312 final Object mCurrentOpLock = new Object();
313 final Random mTokenGenerator = new Random();
314
Christopher Tate4a627c72011-04-01 14:43:32 -0700315 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
316
Christopher Tate5cb400b2009-06-25 16:03:14 -0700317 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700318 File mBaseStateDir;
319 File mDataDir;
320 File mJournalDir;
321 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700322
Christopher Tate84725812010-02-04 15:52:40 -0800323 // Keep a log of all the apps we've ever backed up, and what the
324 // dataset tokens are for both the current backup dataset and
325 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700326 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700327 HashSet<String> mEverStoredApps = new HashSet<String>();
328
Christopher Tateb49ceb32010-02-08 16:22:24 -0800329 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800330 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800331 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800332 long mAncestralToken = 0;
333 long mCurrentToken = 0;
334
Christopher Tate4cc86e12009-09-21 19:36:51 -0700335 // Persistently track the need to do a full init
336 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
337 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700338
Christopher Tate4a627c72011-04-01 14:43:32 -0700339 // Utility: build a new random integer token
340 int generateToken() {
341 int token;
342 do {
343 synchronized (mTokenGenerator) {
344 token = mTokenGenerator.nextInt();
345 }
346 } while (token < 0);
347 return token;
348 }
349
Christopher Tate44a27902010-01-27 17:15:49 -0800350 // ----- Asynchronous backup/restore handler thread -----
351
352 private class BackupHandler extends Handler {
353 public BackupHandler(Looper looper) {
354 super(looper);
355 }
356
357 public void handleMessage(Message msg) {
358
359 switch (msg.what) {
360 case MSG_RUN_BACKUP:
361 {
362 mLastBackupPass = System.currentTimeMillis();
363 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
364
365 IBackupTransport transport = getTransport(mCurrentTransport);
366 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800367 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800368 mWakelock.release();
369 break;
370 }
371
372 // snapshot the pending-backup set and work on that
373 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800374 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800375 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800376 // Do we have any work to do? Construct the work queue
377 // then release the synchronization lock to actually run
378 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800379 if (mPendingBackups.size() > 0) {
380 for (BackupRequest b: mPendingBackups.values()) {
381 queue.add(b);
382 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800383 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800384 mPendingBackups.clear();
385
386 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800387 mJournal = null;
388
Christopher Tate44a27902010-01-27 17:15:49 -0800389 }
390 }
Christopher Tatec61da312010-02-05 10:41:27 -0800391
392 if (queue.size() > 0) {
393 // At this point, we have started a new journal file, and the old
394 // file identity is being passed to the backup processing thread.
395 // When it completes successfully, that old journal file will be
396 // deleted. If we crash prior to that, the old journal is parsed
397 // at next boot and the journaled requests fulfilled.
398 (new PerformBackupTask(transport, queue, oldJournal)).run();
399 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800400 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800401 mWakelock.release();
402 }
Christopher Tate44a27902010-01-27 17:15:49 -0800403 break;
404 }
405
406 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700407 {
408 FullBackupParams params = (FullBackupParams)msg.obj;
409 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
410 params.includeShared, params.allApps, params.packages,
411 params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800412 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700413 }
Christopher Tate44a27902010-01-27 17:15:49 -0800414
415 case MSG_RUN_RESTORE:
416 {
417 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800418 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800419 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700420 params.token, params.pkgInfo, params.pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -0700421 params.needFullBackup, params.filterSet)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800422 break;
423 }
424
Christopher Tate75a99702011-05-18 16:28:19 -0700425 case MSG_RUN_FULL_RESTORE:
426 {
427 FullRestoreParams params = (FullRestoreParams)msg.obj;
428 (new PerformFullRestoreTask(params.fd, params.observer, params.latch)).run();
429 break;
430 }
431
Christopher Tate44a27902010-01-27 17:15:49 -0800432 case MSG_RUN_CLEAR:
433 {
434 ClearParams params = (ClearParams)msg.obj;
435 (new PerformClearTask(params.transport, params.packageInfo)).run();
436 break;
437 }
438
439 case MSG_RUN_INITIALIZE:
440 {
441 HashSet<String> queue;
442
443 // Snapshot the pending-init queue and work on that
444 synchronized (mQueueLock) {
445 queue = new HashSet<String>(mPendingInits);
446 mPendingInits.clear();
447 }
448
449 (new PerformInitializeTask(queue)).run();
450 break;
451 }
452
Christopher Tate2d449afe2010-03-29 19:14:24 -0700453 case MSG_RUN_GET_RESTORE_SETS:
454 {
455 // Like other async operations, this is entered with the wakelock held
456 RestoreSet[] sets = null;
457 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
458 try {
459 sets = params.transport.getAvailableRestoreSets();
460 // cache the result in the active session
461 synchronized (params.session) {
462 params.session.mRestoreSets = sets;
463 }
464 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
465 } catch (Exception e) {
466 Slog.e(TAG, "Error from transport getting set list");
467 } finally {
468 if (params.observer != null) {
469 try {
470 params.observer.restoreSetsAvailable(sets);
471 } catch (RemoteException re) {
472 Slog.e(TAG, "Unable to report listing to observer");
473 } catch (Exception e) {
474 Slog.e(TAG, "Restore observer threw", e);
475 }
476 }
477
Christopher Tate2a935092011-03-03 17:30:32 -0800478 // Done: reset the session timeout clock
479 removeMessages(MSG_RESTORE_TIMEOUT);
480 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
481
Christopher Tate2d449afe2010-03-29 19:14:24 -0700482 mWakelock.release();
483 }
484 break;
485 }
486
Christopher Tate44a27902010-01-27 17:15:49 -0800487 case MSG_TIMEOUT:
488 {
489 synchronized (mCurrentOpLock) {
490 final int token = msg.arg1;
491 int state = mCurrentOperations.get(token, OP_TIMEOUT);
492 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800493 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800494 mCurrentOperations.put(token, OP_TIMEOUT);
495 }
496 mCurrentOpLock.notifyAll();
497 }
498 break;
499 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800500
501 case MSG_RESTORE_TIMEOUT:
502 {
503 synchronized (BackupManagerService.this) {
504 if (mActiveRestoreSession != null) {
505 // Client app left the restore session dangling. We know that it
506 // can't be in the middle of an actual restore operation because
507 // those are executed serially on this same handler thread. Clean
508 // up now.
509 Slog.w(TAG, "Restore session timed out; aborting");
510 post(mActiveRestoreSession.new EndRestoreRunnable(
511 BackupManagerService.this, mActiveRestoreSession));
512 }
513 }
514 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700515
516 case MSG_FULL_CONFIRMATION_TIMEOUT:
517 {
518 synchronized (mFullConfirmations) {
519 FullParams params = mFullConfirmations.get(msg.arg1);
520 if (params != null) {
521 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
522
523 // Release the waiter; timeout == completion
524 signalFullBackupRestoreCompletion(params);
525
526 // Remove the token from the set
527 mFullConfirmations.delete(msg.arg1);
528
529 // Report a timeout to the observer, if any
530 if (params.observer != null) {
531 try {
532 params.observer.onTimeout();
533 } catch (RemoteException e) {
534 /* don't care if the app has gone away */
535 }
536 }
537 } else {
538 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
539 }
540 }
541 break;
542 }
Christopher Tate44a27902010-01-27 17:15:49 -0800543 }
544 }
545 }
546
547 // ----- Main service implementation -----
548
Christopher Tate487529a2009-04-29 14:03:25 -0700549 public BackupManagerService(Context context) {
550 mContext = context;
551 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700552 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700553 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700554
Christopher Tateb6787f22009-07-02 17:40:45 -0700555 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
556 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
557
Christopher Tate44a27902010-01-27 17:15:49 -0800558 mBackupManagerBinder = asInterface(asBinder());
559
560 // spin up the backup/restore handler thread
561 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
562 mHandlerThread.start();
563 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
564
Christopher Tate22b87872009-05-04 16:41:53 -0700565 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700566 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700567 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700568 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700569 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800570 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800571 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800572 // If Encrypted file systems is enabled or disabled, this call will return the
573 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600574 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800575 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700576 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700577
Christopher Tate4cc86e12009-09-21 19:36:51 -0700578 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700579 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700580 IntentFilter filter = new IntentFilter();
581 filter.addAction(RUN_BACKUP_ACTION);
582 context.registerReceiver(mRunBackupReceiver, filter,
583 android.Manifest.permission.BACKUP, null);
584
585 mRunInitReceiver = new RunInitializeReceiver();
586 filter = new IntentFilter();
587 filter.addAction(RUN_INITIALIZE_ACTION);
588 context.registerReceiver(mRunInitReceiver, filter,
589 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700590
591 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700592 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
593 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
594
Christopher Tate4cc86e12009-09-21 19:36:51 -0700595 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
596 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
597 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
598
Christopher Tatecde87f42009-06-12 12:55:53 -0700599 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700600 mJournalDir = new File(mBaseStateDir, "pending");
601 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700602 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700603
Christopher Tate73e02522009-07-15 14:18:26 -0700604 // Set up the various sorts of package tracking we do
605 initPackageTracking();
606
Christopher Tateabce4e82009-06-18 18:35:32 -0700607 // Build our mapping of uid to backup client services. This implicitly
608 // schedules a backup pass on the Package Manager metadata the first
609 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700610 synchronized (mBackupParticipants) {
611 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700612 }
613
Dan Egnor87a02bc2009-06-17 02:30:10 -0700614 // Set up our transport options and initialize the default transport
615 // TODO: Have transports register themselves somehow?
616 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700617 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700618 ComponentName localName = new ComponentName(context, LocalTransport.class);
619 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700620
Christopher Tate91717492009-06-26 21:07:13 -0700621 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700622 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
623 Settings.Secure.BACKUP_TRANSPORT);
624 if ("".equals(mCurrentTransport)) {
625 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700626 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800627 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700628
629 // Attach to the Google backup transport. When this comes up, it will set
630 // itself as the current transport because we explicitly reset mCurrentTransport
631 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700632 ComponentName transportComponent = new ComponentName("com.google.android.backup",
633 "com.google.android.backup.BackupTransportService");
634 try {
635 // If there's something out there that is supposed to be the Google
636 // backup transport, make sure it's legitimately part of the OS build
637 // and not an app lying about its package name.
638 ApplicationInfo info = mPackageManager.getApplicationInfo(
639 transportComponent.getPackageName(), 0);
640 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
641 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
642 Intent intent = new Intent().setComponent(transportComponent);
643 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
644 } else {
645 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
646 }
647 } catch (PackageManager.NameNotFoundException nnf) {
648 // No such package? No binding.
649 if (DEBUG) Slog.v(TAG, "Google transport not present");
650 }
Christopher Tateaa088442009-06-16 18:25:46 -0700651
Christopher Tatecde87f42009-06-12 12:55:53 -0700652 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700653 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700654 parseLeftoverJournals();
655
Christopher Tateb6787f22009-07-02 17:40:45 -0700656 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700657 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700658
659 // Start the backup passes going
660 setBackupEnabled(areEnabled);
661 }
662
663 private class RunBackupReceiver extends BroadcastReceiver {
664 public void onReceive(Context context, Intent intent) {
665 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700666 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700667 if (mPendingInits.size() > 0) {
668 // If there are pending init operations, we process those
669 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800670 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700671 try {
672 mAlarmManager.cancel(mRunInitIntent);
673 mRunInitIntent.send();
674 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800675 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700676 // can't really do more than bail here
677 }
678 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800679 // Don't run backups now if we're disabled or not yet
680 // fully set up.
681 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800682 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700683
684 // Acquire the wakelock and pass it to the backup thread. it will
685 // be released once backup concludes.
686 mWakelock.acquire();
687
688 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
689 mBackupHandler.sendMessage(msg);
690 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800691 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700692 }
693 }
694 }
695 }
696 }
697 }
698
699 private class RunInitializeReceiver extends BroadcastReceiver {
700 public void onReceive(Context context, Intent intent) {
701 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
702 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800703 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700704
705 // Acquire the wakelock and pass it to the init thread. it will
706 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700707 mWakelock.acquire();
708
Christopher Tate4cc86e12009-09-21 19:36:51 -0700709 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700710 mBackupHandler.sendMessage(msg);
711 }
712 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700713 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700714 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700715
Christopher Tate73e02522009-07-15 14:18:26 -0700716 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800717 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700718
Christopher Tate84725812010-02-04 15:52:40 -0800719 // Remember our ancestral dataset
720 mTokenFile = new File(mBaseStateDir, "ancestral");
721 try {
722 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800723 int version = tf.readInt();
724 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
725 mAncestralToken = tf.readLong();
726 mCurrentToken = tf.readLong();
727
728 int numPackages = tf.readInt();
729 if (numPackages >= 0) {
730 mAncestralPackages = new HashSet<String>();
731 for (int i = 0; i < numPackages; i++) {
732 String pkgName = tf.readUTF();
733 mAncestralPackages.add(pkgName);
734 }
735 }
736 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800737 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800738 } catch (FileNotFoundException fnf) {
739 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800740 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800741 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800742 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800743 }
744
Christopher Tatee97e8072009-07-15 16:45:50 -0700745 // Keep a log of what apps we've ever backed up. Because we might have
746 // rebooted in the middle of an operation that was removing something from
747 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700748 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700749 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700750
Christopher Tatee97e8072009-07-15 16:45:50 -0700751 // If we were in the middle of removing something from the ever-backed-up
752 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700753 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700754 if (tempProcessedFile.exists()) {
755 tempProcessedFile.delete();
756 }
757
Dan Egnor852f8e42009-09-30 11:20:45 -0700758 // If there are previous contents, parse them out then start a new
759 // file to continue the recordkeeping.
760 if (mEverStored.exists()) {
761 RandomAccessFile temp = null;
762 RandomAccessFile in = null;
763
764 try {
765 temp = new RandomAccessFile(tempProcessedFile, "rws");
766 in = new RandomAccessFile(mEverStored, "r");
767
768 while (true) {
769 PackageInfo info;
770 String pkg = in.readUTF();
771 try {
772 info = mPackageManager.getPackageInfo(pkg, 0);
773 mEverStoredApps.add(pkg);
774 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800775 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700776 } catch (NameNotFoundException e) {
777 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800778 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700779 }
780 }
781 } catch (EOFException e) {
782 // Once we've rewritten the backup history log, atomically replace the
783 // old one with the new one then reopen the file for continuing use.
784 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800785 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700786 }
787 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800788 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700789 } finally {
790 try { if (temp != null) temp.close(); } catch (IOException e) {}
791 try { if (in != null) in.close(); } catch (IOException e) {}
792 }
793 }
794
Christopher Tate73e02522009-07-15 14:18:26 -0700795 // Register for broadcasts about package install, etc., so we can
796 // update the provider list.
797 IntentFilter filter = new IntentFilter();
798 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
799 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
800 filter.addDataScheme("package");
801 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800802 // Register for events related to sdcard installation.
803 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800804 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
805 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800806 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700807 }
808
Christopher Tatecde87f42009-06-12 12:55:53 -0700809 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700810 for (File f : mJournalDir.listFiles()) {
811 if (mJournal == null || f.compareTo(mJournal) != 0) {
812 // This isn't the current journal, so it must be a leftover. Read
813 // out the package names mentioned there and schedule them for
814 // backup.
815 RandomAccessFile in = null;
816 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400817 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700818 in = new RandomAccessFile(f, "r");
819 while (true) {
820 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400821 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700822 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700823 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700824 } catch (EOFException e) {
825 // no more data; we're done
826 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800827 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700828 } finally {
829 // close/delete the file
830 try { if (in != null) in.close(); } catch (IOException e) {}
831 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700832 }
833 }
834 }
835 }
836
Christopher Tate4cc86e12009-09-21 19:36:51 -0700837 // Maintain persistent state around whether need to do an initialize operation.
838 // Must be called with the queue lock held.
839 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800840 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700841 + " on transport " + transportName);
842 try {
843 IBackupTransport transport = getTransport(transportName);
844 String transportDirName = transport.transportDirName();
845 File stateDir = new File(mBaseStateDir, transportDirName);
846 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
847
848 if (isPending) {
849 // We need an init before we can proceed with sending backup data.
850 // Record that with an entry in our set of pending inits, as well as
851 // journaling it via creation of a sentinel file.
852 mPendingInits.add(transportName);
853 try {
854 (new FileOutputStream(initPendingFile)).close();
855 } catch (IOException ioe) {
856 // Something is badly wrong with our permissions; just try to move on
857 }
858 } else {
859 // No more initialization needed; wipe the journal and reset our state.
860 initPendingFile.delete();
861 mPendingInits.remove(transportName);
862 }
863 } catch (RemoteException e) {
864 // can't happen; the transport is local
865 }
866 }
867
Christopher Tated55e18a2009-09-21 10:12:59 -0700868 // Reset all of our bookkeeping, in response to having been told that
869 // the backend data has been wiped [due to idle expiry, for example],
870 // so we must re-upload all saved settings.
871 void resetBackupState(File stateFileDir) {
872 synchronized (mQueueLock) {
873 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700874 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700875 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700876
Christopher Tate84725812010-02-04 15:52:40 -0800877 mCurrentToken = 0;
878 writeRestoreTokens();
879
Christopher Tated55e18a2009-09-21 10:12:59 -0700880 // Remove all the state files
881 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700882 // ... but don't touch the needs-init sentinel
883 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
884 sf.delete();
885 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700886 }
Christopher Tate45597642011-04-04 16:59:21 -0700887 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700888
Christopher Tate45597642011-04-04 16:59:21 -0700889 // Enqueue a new backup of every participant
890 int N = mBackupParticipants.size();
891 for (int i=0; i<N; i++) {
892 int uid = mBackupParticipants.keyAt(i);
893 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
894 for (ApplicationInfo app: participants) {
895 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700896 }
897 }
898 }
899
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800900 // Add a transport to our set of available backends. If 'transport' is null, this
901 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700902 private void registerTransport(String name, IBackupTransport transport) {
903 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800904 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800905 if (transport != null) {
906 mTransports.put(name, transport);
907 } else {
908 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800909 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800910 mCurrentTransport = null;
911 }
912 // Nothing further to do in the unregistration case
913 return;
914 }
Christopher Tate91717492009-06-26 21:07:13 -0700915 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700916
917 // If the init sentinel file exists, we need to be sure to perform the init
918 // as soon as practical. We also create the state directory at registration
919 // time to ensure it's present from the outset.
920 try {
921 String transportName = transport.transportDirName();
922 File stateDir = new File(mBaseStateDir, transportName);
923 stateDir.mkdirs();
924
925 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
926 if (initSentinel.exists()) {
927 synchronized (mQueueLock) {
928 mPendingInits.add(transportName);
929
930 // TODO: pick a better starting time than now + 1 minute
931 long delay = 1000 * 60; // one minute, in milliseconds
932 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
933 System.currentTimeMillis() + delay, mRunInitIntent);
934 }
935 }
936 } catch (RemoteException e) {
937 // can't happen, the transport is local
938 }
Christopher Tate91717492009-06-26 21:07:13 -0700939 }
940
Christopher Tate3799bc22009-05-06 16:13:56 -0700941 // ----- Track installation/removal of packages -----
942 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
943 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800944 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700945
Christopher Tate3799bc22009-05-06 16:13:56 -0700946 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800947 boolean replacing = false;
948 boolean added = false;
949 Bundle extras = intent.getExtras();
950 String pkgList[] = null;
951 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
952 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
953 Uri uri = intent.getData();
954 if (uri == null) {
955 return;
956 }
957 String pkgName = uri.getSchemeSpecificPart();
958 if (pkgName != null) {
959 pkgList = new String[] { pkgName };
960 }
961 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
962 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800963 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800964 added = true;
965 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800966 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800967 added = false;
968 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
969 }
970 if (pkgList == null || pkgList.length == 0) {
971 return;
972 }
973 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700974 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800975 for (String pkgName : pkgList) {
976 if (replacing) {
977 // The package was just upgraded
978 updatePackageParticipantsLocked(pkgName);
979 } else {
980 // The package was just added
981 addPackageParticipantsLocked(pkgName);
982 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700983 }
984 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800985 } else {
986 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700987 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
988 } else {
989 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800990 for (String pkgName : pkgList) {
991 removePackageParticipantsLocked(pkgName);
992 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700993 }
994 }
995 }
996 }
997 };
998
Dan Egnor87a02bc2009-06-17 02:30:10 -0700999 // ----- Track connection to GoogleBackupTransport service -----
1000 ServiceConnection mGoogleConnection = new ServiceConnection() {
1001 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001002 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001003 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -07001004 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001005 }
1006
1007 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001008 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -07001009 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -07001010 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -07001011 }
1012 };
1013
Christopher Tate181fafa2009-05-14 11:12:14 -07001014 // Add the backup agents in the given package to our set of known backup participants.
1015 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -07001016 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001017 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -08001018 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -07001019 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -07001020 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001021 }
1022
Christopher Tate181fafa2009-05-14 11:12:14 -07001023 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -07001024 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001025 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001026 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -07001027 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001028 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001029 + " uid=" + p.applicationInfo.uid
1030 + " killAfterRestore="
1031 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001032 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001033 }
1034 }
1035
Dan Egnorefe52642009-06-24 00:16:33 -07001036 for (PackageInfo pkg : targetPkgs) {
1037 if (packageName == null || pkg.packageName.equals(packageName)) {
1038 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001039 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001040 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001041 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001042 mBackupParticipants.put(uid, set);
1043 }
Dan Egnorefe52642009-06-24 00:16:33 -07001044 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001045
1046 // If we've never seen this app before, schedule a backup for it
1047 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001048 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001049 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001050 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001051 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001052 }
Christopher Tate487529a2009-04-29 14:03:25 -07001053 }
1054 }
1055
Christopher Tate6785dd82009-06-18 15:58:25 -07001056 // Remove the given package's entry from our known active set. If
1057 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001058 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001059 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001060 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001061 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001062 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001063 } else {
1064 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001065 List<PackageInfo> knownPackages = allAgentPackages();
1066 for (PackageInfo pkg : knownPackages) {
1067 allApps.add(pkg.packageName);
1068 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001069 }
1070 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001071 }
1072
Joe Onorato8ad02812009-05-13 01:41:44 -04001073 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001074 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001075 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001076 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001077 + ") removing " + allPackageNames.size() + " entries");
1078 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001079 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001080 }
1081 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001082 for (String pkg : allPackageNames) {
1083 if (packageName == null || pkg.equals(packageName)) {
1084 int uid = -1;
1085 try {
1086 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1087 uid = info.applicationInfo.uid;
1088 } catch (NameNotFoundException e) {
1089 // we don't know this package name, so just skip it for now
1090 continue;
1091 }
1092
Christopher Tate181fafa2009-05-14 11:12:14 -07001093 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001094 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001095 // Find the existing entry with the same package name, and remove it.
1096 // We can't just remove(app) because the instances are different.
1097 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001098 if (entry.packageName.equals(pkg)) {
1099 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001100 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001101 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001102 break;
1103 }
1104 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001105 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001106 mBackupParticipants.delete(uid);
1107 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001108 }
1109 }
1110 }
1111 }
1112
Christopher Tate181fafa2009-05-14 11:12:14 -07001113 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001114 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001115 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001116 int flags = PackageManager.GET_SIGNATURES;
1117 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1118 int N = packages.size();
1119 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001120 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001121 try {
1122 ApplicationInfo app = pkg.applicationInfo;
1123 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001124 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001125 packages.remove(a);
1126 }
1127 else {
1128 // we will need the shared library path, so look that up and store it here
1129 app = mPackageManager.getApplicationInfo(pkg.packageName,
1130 PackageManager.GET_SHARED_LIBRARY_FILES);
1131 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1132 }
1133 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001134 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001135 }
1136 }
Dan Egnorefe52642009-06-24 00:16:33 -07001137 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001138 }
Christopher Tateaa088442009-06-16 18:25:46 -07001139
Christopher Tate3799bc22009-05-06 16:13:56 -07001140 // Reset the given package's known backup participants. Unlike add/remove, the update
1141 // action cannot be passed a null package name.
1142 void updatePackageParticipantsLocked(String packageName) {
1143 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001144 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001145 return;
1146 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001147 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001148
1149 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001150 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001151 List<String> allAppNames = new ArrayList<String>();
1152 for (PackageInfo pkg : allApps) {
1153 allAppNames.add(pkg.packageName);
1154 }
1155 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001156 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001157 }
1158
Christopher Tate84725812010-02-04 15:52:40 -08001159 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001160 // backed up at least once
1161 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001162 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1163
1164 synchronized (mEverStoredApps) {
1165 if (!mEverStoredApps.add(packageName)) return;
1166
1167 RandomAccessFile out = null;
1168 try {
1169 out = new RandomAccessFile(mEverStored, "rws");
1170 out.seek(out.length());
1171 out.writeUTF(packageName);
1172 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001173 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001174 } finally {
1175 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001176 }
1177 }
1178 }
1179
Christopher Tatee97e8072009-07-15 16:45:50 -07001180 // Remove our awareness of having ever backed up the given package
1181 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001182 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001183
Dan Egnor852f8e42009-09-30 11:20:45 -07001184 synchronized (mEverStoredApps) {
1185 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1186 // we'll recognize on initialization time that the package no longer
1187 // exists and fix it up then.
1188 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1189 RandomAccessFile known = null;
1190 try {
1191 known = new RandomAccessFile(tempKnownFile, "rws");
1192 mEverStoredApps.remove(packageName);
1193 for (String s : mEverStoredApps) {
1194 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001195 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001196 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001197 known.close();
1198 known = null;
1199 if (!tempKnownFile.renameTo(mEverStored)) {
1200 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1201 }
1202 } catch (IOException e) {
1203 // Bad: we couldn't create the new copy. For safety's sake we
1204 // abandon the whole process and remove all what's-backed-up
1205 // state entirely, meaning we'll force a backup pass for every
1206 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001207 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001208 mEverStoredApps.clear();
1209 tempKnownFile.delete();
1210 mEverStored.delete();
1211 } finally {
1212 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001213 }
1214 }
1215 }
1216
Christopher Tateb49ceb32010-02-08 16:22:24 -08001217 // Persistently record the current and ancestral backup tokens as well
1218 // as the set of packages with data [supposedly] available in the
1219 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001220 void writeRestoreTokens() {
1221 try {
1222 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001223
1224 // First, the version number of this record, for futureproofing
1225 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1226
1227 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001228 af.writeLong(mAncestralToken);
1229 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001230
1231 // Now write the set of ancestral packages
1232 if (mAncestralPackages == null) {
1233 af.writeInt(-1);
1234 } else {
1235 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001236 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001237 for (String pkgName : mAncestralPackages) {
1238 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001239 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001240 }
1241 }
Christopher Tate84725812010-02-04 15:52:40 -08001242 af.close();
1243 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001244 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001245 }
1246 }
1247
Dan Egnor87a02bc2009-06-17 02:30:10 -07001248 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001249 private IBackupTransport getTransport(String transportName) {
1250 synchronized (mTransports) {
1251 IBackupTransport transport = mTransports.get(transportName);
1252 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001253 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001254 }
1255 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001256 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001257 }
1258
Christopher Tatedf01dea2009-06-09 20:45:02 -07001259 // fire off a backup agent, blocking until it attaches or times out
1260 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1261 IBackupAgent agent = null;
1262 synchronized(mAgentConnectLock) {
1263 mConnecting = true;
1264 mConnectedAgent = null;
1265 try {
1266 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001267 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001268
1269 // success; wait for the agent to arrive
Christopher Tate75a99702011-05-18 16:28:19 -07001270 // only wait 10 seconds for the bind to happen
Christopher Tatec7b31e32009-06-10 15:49:30 -07001271 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1272 while (mConnecting && mConnectedAgent == null
1273 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001274 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001275 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001276 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001277 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001278 return null;
1279 }
1280 }
1281
1282 // if we timed out with no connect, abort and move on
1283 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001284 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001285 return null;
1286 }
1287 agent = mConnectedAgent;
1288 }
1289 } catch (RemoteException e) {
1290 // can't happen
1291 }
1292 }
1293 return agent;
1294 }
1295
Christopher Tatec7b31e32009-06-10 15:49:30 -07001296 // clear an application's data, blocking until the operation completes or times out
1297 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001298 // Don't wipe packages marked allowClearUserData=false
1299 try {
1300 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1301 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001302 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001303 + packageName);
1304 return;
1305 }
1306 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001307 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001308 return;
1309 }
1310
Christopher Tatec7b31e32009-06-10 15:49:30 -07001311 ClearDataObserver observer = new ClearDataObserver();
1312
1313 synchronized(mClearDataLock) {
1314 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001315 try {
1316 mActivityManager.clearApplicationUserData(packageName, observer);
1317 } catch (RemoteException e) {
1318 // can't happen because the activity manager is in this process
1319 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001320
1321 // only wait 10 seconds for the clear data to happen
1322 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1323 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1324 try {
1325 mClearDataLock.wait(5000);
1326 } catch (InterruptedException e) {
1327 // won't happen, but still.
1328 mClearingData = false;
1329 }
1330 }
1331 }
1332 }
1333
1334 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001335 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001336 synchronized(mClearDataLock) {
1337 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001338 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001339 }
1340 }
1341 }
1342
Christopher Tate1bb69062010-02-19 17:02:12 -08001343 // Get the restore-set token for the best-available restore set for this package:
1344 // the active set if possible, else the ancestral one. Returns zero if none available.
1345 long getAvailableRestoreToken(String packageName) {
1346 long token = mAncestralToken;
1347 synchronized (mQueueLock) {
1348 if (mEverStoredApps.contains(packageName)) {
1349 token = mCurrentToken;
1350 }
1351 }
1352 return token;
1353 }
1354
Christopher Tate44a27902010-01-27 17:15:49 -08001355 // -----
1356 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1357 boolean waitUntilOperationComplete(int token) {
1358 int finalState = OP_PENDING;
1359 synchronized (mCurrentOpLock) {
1360 try {
1361 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1362 try {
1363 mCurrentOpLock.wait();
1364 } catch (InterruptedException e) {}
1365 }
1366 } catch (IndexOutOfBoundsException e) {
1367 // the operation has been mysteriously cleared from our
1368 // bookkeeping -- consider this a success and ignore it.
1369 }
1370 }
1371 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001372 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001373 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001374 return finalState == OP_ACKNOWLEDGED;
1375 }
1376
1377 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001378 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001379 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001380 synchronized (mCurrentOpLock) {
1381 mCurrentOperations.put(token, OP_PENDING);
1382 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1383 mBackupHandler.sendMessageDelayed(msg, interval);
1384 }
Christopher Tate44a27902010-01-27 17:15:49 -08001385 }
1386
Christopher Tate043dadc2009-06-02 16:11:00 -07001387 // ----- Back up a set of applications via a worker thread -----
1388
Christopher Tate44a27902010-01-27 17:15:49 -08001389 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001390 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001391 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001392 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001393 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001394 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001395
Christopher Tate44a27902010-01-27 17:15:49 -08001396 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001397 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001398 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001399 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001400 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001401
1402 try {
1403 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1404 } catch (RemoteException e) {
1405 // can't happen; the transport is local
1406 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001407 }
1408
Christopher Tate043dadc2009-06-02 16:11:00 -07001409 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001410 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001411 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001412 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001413
Christopher Tate79588342009-06-30 16:11:49 -07001414 // Backups run at background priority
1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416
Christopher Tate043dadc2009-06-02 16:11:00 -07001417 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001418 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001419
Dan Egnor852f8e42009-09-30 11:20:45 -07001420 // If we haven't stored package manager metadata yet, we must init the transport.
1421 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1422 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001423 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001424 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001425 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001426 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001427 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001428 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001429 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001430 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001431 }
Dan Egnor01445162009-09-21 17:04:05 -07001432 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001433
1434 // The package manager doesn't have a proper <application> etc, but since
1435 // it's running here in the system process we can just set up its agent
1436 // directly and use a synthetic BackupRequest. We always run this pass
1437 // because it's cheap and this way we guarantee that we don't get out of
1438 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001439 if (status == BackupConstants.TRANSPORT_OK) {
1440 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1441 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001442 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001443 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1444 status = processOneBackup(pmRequest,
1445 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1446 }
Christopher Tate90967f42009-09-20 15:28:33 -07001447
Dan Egnor01445162009-09-21 17:04:05 -07001448 if (status == BackupConstants.TRANSPORT_OK) {
1449 // Now run all the backups in our queue
1450 status = doQueuedBackups(mTransport);
1451 }
1452
1453 if (status == BackupConstants.TRANSPORT_OK) {
1454 // Tell the transport to finish everything it has buffered
1455 status = mTransport.finishBackup();
1456 if (status == BackupConstants.TRANSPORT_OK) {
1457 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001458 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001459 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001460 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001461 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001462 }
1463 }
1464
Dan Egnor01445162009-09-21 17:04:05 -07001465 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001466 // The backend reports that our dataset has been wiped. We need to
1467 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001468 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001469 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001470 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001471 }
1472 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001473 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001474 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001475 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001476 // If everything actually went through and this is the first time we've
1477 // done a backup, we can now record what the current backup dataset token
1478 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001479 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001480 try {
1481 mCurrentToken = mTransport.getCurrentRestoreSet();
1482 } catch (RemoteException e) { /* cannot happen */ }
1483 writeRestoreTokens();
1484 }
1485
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001486 // If things went wrong, we need to re-stage the apps we had expected
1487 // to be backing up in this pass. This journals the package names in
1488 // the current active pending-backup file, not in the we are holding
1489 // here in mJournal.
1490 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001491 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001492 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001493 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001494 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001495
1496 // We also want to reset the backup schedule based on whatever
1497 // the transport suggests by way of retry/backoff time.
1498 try {
1499 startBackupAlarmsLocked(mTransport.requestBackupTime());
1500 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001501 }
1502
1503 // Either backup was successful, in which case we of course do not need
1504 // this pass's journal any more; or it failed, in which case we just
1505 // re-enqueued all of these packages in the current active journal.
1506 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001507 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001508 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001509 }
1510
Christopher Tatec2af5d32010-02-02 15:18:58 -08001511 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001512 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001513 backupNow();
1514 }
1515
Dan Egnorbb9001c2009-07-27 12:20:13 -07001516 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001517 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001518 }
1519
Dan Egnor01445162009-09-21 17:04:05 -07001520 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001521 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001522 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001523
Christopher Tatec28083a2010-12-14 16:16:44 -08001524 // Verify that the requested app exists; it might be something that
1525 // requested a backup but was then uninstalled. The request was
1526 // journalled and rather than tamper with the journal it's safer
1527 // to sanity-check here.
1528 try {
1529 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1530 } catch (NameNotFoundException e) {
1531 Slog.d(TAG, "Package does not exist; skipping");
1532 continue;
1533 }
1534
Christopher Tate043dadc2009-06-02 16:11:00 -07001535 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001536 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001537 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001538 agent = bindToAgentSynchronous(request.appInfo,
1539 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001540 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001541 int result = processOneBackup(request, agent, transport);
1542 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001543 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001544 } catch (SecurityException ex) {
1545 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001546 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001547 } finally {
1548 try { // unbind even on timeout, just in case
1549 mActivityManager.unbindBackupAgent(request.appInfo);
1550 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001551 }
1552 }
Dan Egnor01445162009-09-21 17:04:05 -07001553
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001554 mWakelock.setWorkSource(null);
1555
Dan Egnor01445162009-09-21 17:04:05 -07001556 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001557 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001558
Dan Egnor01445162009-09-21 17:04:05 -07001559 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1560 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001561 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001562 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001563
Dan Egnorbb9001c2009-07-27 12:20:13 -07001564 File savedStateName = new File(mStateDir, packageName);
1565 File backupDataName = new File(mDataDir, packageName + ".data");
1566 File newStateName = new File(mStateDir, packageName + ".new");
1567
1568 ParcelFileDescriptor savedState = null;
1569 ParcelFileDescriptor backupData = null;
1570 ParcelFileDescriptor newState = null;
1571
1572 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001573 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001574 try {
1575 // Look up the package info & signatures. This is first so that if it
1576 // throws an exception, there's no file setup yet that would need to
1577 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001578 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1579 // The metadata 'package' is synthetic
1580 packInfo = new PackageInfo();
1581 packInfo.packageName = packageName;
1582 } else {
1583 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001584 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001585 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001586
Christopher Tatec7b31e32009-06-10 15:49:30 -07001587 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001588 // the saved-state "file". This is by definition an incremental,
1589 // so we build a saved state file to pass.
1590 savedState = ParcelFileDescriptor.open(savedStateName,
1591 ParcelFileDescriptor.MODE_READ_ONLY |
1592 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001593
Dan Egnorbb9001c2009-07-27 12:20:13 -07001594 backupData = ParcelFileDescriptor.open(backupDataName,
1595 ParcelFileDescriptor.MODE_READ_WRITE |
1596 ParcelFileDescriptor.MODE_CREATE |
1597 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001598
Dan Egnorbb9001c2009-07-27 12:20:13 -07001599 newState = ParcelFileDescriptor.open(newStateName,
1600 ParcelFileDescriptor.MODE_READ_WRITE |
1601 ParcelFileDescriptor.MODE_CREATE |
1602 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001603
Christopher Tate44a27902010-01-27 17:15:49 -08001604 // Initiate the target's backup pass
1605 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001606 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001607 boolean success = waitUntilOperationComplete(token);
1608
1609 if (!success) {
1610 // timeout -- bail out into the failed-transaction logic
1611 throw new RuntimeException("Backup timeout");
1612 }
1613
Dan Egnorbb9001c2009-07-27 12:20:13 -07001614 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001615 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001616 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001617 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001618 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001619 backupDataName.delete();
1620 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001621 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001622 } finally {
1623 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1624 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1625 try { if (newState != null) newState.close(); } catch (IOException e) {}
1626 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001627 synchronized (mCurrentOpLock) {
1628 mCurrentOperations.clear();
1629 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001630 }
1631
1632 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001633 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001634 try {
1635 int size = (int) backupDataName.length();
1636 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001637 if (result == BackupConstants.TRANSPORT_OK) {
1638 backupData = ParcelFileDescriptor.open(backupDataName,
1639 ParcelFileDescriptor.MODE_READ_ONLY);
1640 result = transport.performBackup(packInfo, backupData);
1641 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001642
Dan Egnor83861e72009-09-17 16:17:55 -07001643 // TODO - We call finishBackup() for each application backed up, because
1644 // we need to know now whether it succeeded or failed. Instead, we should
1645 // hold off on finishBackup() until the end, which implies holding off on
1646 // renaming *all* the output state files (see below) until that happens.
1647
Dan Egnor01445162009-09-21 17:04:05 -07001648 if (result == BackupConstants.TRANSPORT_OK) {
1649 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001650 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001651 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001652 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001653 }
1654
1655 // After successful transport, delete the now-stale data
1656 // and juggle the files so that next time we supply the agent
1657 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001658 if (result == BackupConstants.TRANSPORT_OK) {
1659 backupDataName.delete();
1660 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001661 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001662 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001663 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001664 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001665 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001666 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001667 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001668 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001669 } finally {
1670 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001671 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001672
Dan Egnor01445162009-09-21 17:04:05 -07001673 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001674 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001675 }
1676
Christopher Tatedf01dea2009-06-09 20:45:02 -07001677
Christopher Tate4a627c72011-04-01 14:43:32 -07001678 // ----- Full backup to a file/socket -----
1679
1680 class PerformFullBackupTask implements Runnable {
1681 ParcelFileDescriptor mOutputFile;
1682 IFullBackupRestoreObserver mObserver;
1683 boolean mIncludeApks;
1684 boolean mIncludeShared;
1685 boolean mAllApps;
1686 String[] mPackages;
1687 AtomicBoolean mLatchObject;
1688 File mFilesDir;
1689 File mManifestFile;
1690
1691 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
1692 boolean includeApks, boolean includeShared,
1693 boolean doAllApps, String[] packages, AtomicBoolean latch) {
1694 mOutputFile = fd;
1695 mObserver = observer;
1696 mIncludeApks = includeApks;
1697 mIncludeShared = includeShared;
1698 mAllApps = doAllApps;
1699 mPackages = packages;
1700 mLatchObject = latch;
1701
1702 mFilesDir = new File("/data/system");
1703 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1704 }
1705
1706 @Override
1707 public void run() {
1708 final List<PackageInfo> packagesToBackup;
1709
Christopher Tateb0628bf2011-06-02 15:08:13 -07001710 Slog.i(TAG, "--- Performing full-dataset backup ---");
Christopher Tate4a627c72011-04-01 14:43:32 -07001711 sendStartBackup();
1712
1713 // doAllApps supersedes the package set if any
1714 if (mAllApps) {
1715 packagesToBackup = mPackageManager.getInstalledPackages(
1716 PackageManager.GET_SIGNATURES);
1717 } else {
1718 packagesToBackup = new ArrayList<PackageInfo>();
1719 for (String pkgName : mPackages) {
1720 try {
1721 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
1722 PackageManager.GET_SIGNATURES));
1723 } catch (NameNotFoundException e) {
1724 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
1725 }
1726 }
1727 }
1728
Christopher Tatea858cb02011-06-03 12:27:51 -07001729 // Cull any packages that have indicated that backups are not permitted.
1730 for (int i = 0; i < packagesToBackup.size(); ) {
1731 PackageInfo info = packagesToBackup.get(i);
1732 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
1733 packagesToBackup.remove(i);
1734 } else {
1735 i++;
1736 }
1737 }
1738
Christopher Tate4a627c72011-04-01 14:43:32 -07001739 PackageInfo pkg = null;
1740 try {
Christopher Tateb0628bf2011-06-02 15:08:13 -07001741 // Now back up the app data via the agent mechanism
Christopher Tate4a627c72011-04-01 14:43:32 -07001742 int N = packagesToBackup.size();
1743 for (int i = 0; i < N; i++) {
1744 pkg = packagesToBackup.get(i);
Christopher Tateb0628bf2011-06-02 15:08:13 -07001745 backupOnePackage(pkg);
1746 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001747
Christopher Tateb0628bf2011-06-02 15:08:13 -07001748 // Finally, shared storage if requested
1749 if (mIncludeShared) {
1750 backupSharedStorage();
Christopher Tate4a627c72011-04-01 14:43:32 -07001751 }
1752 } catch (RemoteException e) {
1753 Slog.e(TAG, "App died during full backup");
1754 } finally {
Christopher Tateb0628bf2011-06-02 15:08:13 -07001755 tearDown(pkg);
Christopher Tate4a627c72011-04-01 14:43:32 -07001756 try {
1757 mOutputFile.close();
1758 } catch (IOException e) {
1759 /* nothing we can do about this */
1760 }
1761 synchronized (mCurrentOpLock) {
1762 mCurrentOperations.clear();
1763 }
1764 synchronized (mLatchObject) {
1765 mLatchObject.set(true);
1766 mLatchObject.notifyAll();
1767 }
1768 sendEndBackup();
1769 mWakelock.release();
1770 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
1771 }
1772 }
1773
Christopher Tateb0628bf2011-06-02 15:08:13 -07001774 private void backupOnePackage(PackageInfo pkg) throws RemoteException {
1775 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
1776
1777 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
1778 IApplicationThread.BACKUP_MODE_FULL);
1779 if (agent != null) {
1780 try {
1781 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate79ec80d2011-06-24 14:58:49 -07001782 final boolean sendApk = mIncludeApks
Christopher Tateb0628bf2011-06-02 15:08:13 -07001783 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
1784 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
1785 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
1786
1787 sendOnBackupPackage(pkg.packageName);
1788
Christopher Tate79ec80d2011-06-24 14:58:49 -07001789 BackupDataOutput output = new BackupDataOutput(
1790 mOutputFile.getFileDescriptor());
Christopher Tateb0628bf2011-06-02 15:08:13 -07001791
Christopher Tate79ec80d2011-06-24 14:58:49 -07001792 if (DEBUG) Slog.d(TAG, "Writing manifest for " + pkg.packageName);
1793 writeAppManifest(pkg, mManifestFile, sendApk);
1794 FullBackup.backupToTar(pkg.packageName, null, null,
1795 mFilesDir.getAbsolutePath(),
1796 mManifestFile.getAbsolutePath(),
1797 output);
1798
1799 if (sendApk) {
1800 writeApkToBackup(pkg, output);
Christopher Tateb0628bf2011-06-02 15:08:13 -07001801 }
1802
Christopher Tate79ec80d2011-06-24 14:58:49 -07001803 if (DEBUG) Slog.d(TAG, "Calling doFullBackup()");
Christopher Tateb0628bf2011-06-02 15:08:13 -07001804 final int token = generateToken();
1805 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001806 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07001807 if (!waitUntilOperationComplete(token)) {
1808 Slog.e(TAG, "Full backup failed on package " + pkg.packageName);
1809 } else {
1810 if (DEBUG) Slog.d(TAG, "Full backup success: " + pkg.packageName);
1811 }
1812 } catch (IOException e) {
1813 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
1814 }
1815 } else {
1816 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
1817 }
1818 tearDown(pkg);
1819 }
1820
Christopher Tate79ec80d2011-06-24 14:58:49 -07001821 private void writeApkToBackup(PackageInfo pkg, BackupDataOutput output) {
1822 // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
1823 final String appSourceDir = pkg.applicationInfo.sourceDir;
1824 final String apkDir = new File(appSourceDir).getParent();
1825 FullBackup.backupToTar(pkg.packageName, FullBackup.APK_TREE_TOKEN, null,
1826 apkDir, appSourceDir, output);
1827
1828 // Save associated .obb content if it exists and we did save the apk
1829 // check for .obb and save those too
1830 final File obbDir = Environment.getExternalStorageAppObbDirectory(pkg.packageName);
1831 if (obbDir != null) {
1832 if (DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
1833 File[] obbFiles = obbDir.listFiles();
1834 if (obbFiles != null) {
1835 final String obbDirName = obbDir.getAbsolutePath();
1836 for (File obb : obbFiles) {
1837 FullBackup.backupToTar(pkg.packageName, FullBackup.OBB_TREE_TOKEN, null,
1838 obbDirName, obb.getAbsolutePath(), output);
1839 }
1840 }
1841 }
1842 }
1843
Christopher Tateb0628bf2011-06-02 15:08:13 -07001844 private void backupSharedStorage() throws RemoteException {
1845 PackageInfo pkg = null;
1846 try {
1847 pkg = mPackageManager.getPackageInfo("com.android.sharedstoragebackup", 0);
1848 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
1849 IApplicationThread.BACKUP_MODE_FULL);
1850 if (agent != null) {
1851 sendOnBackupPackage("Shared storage");
1852
1853 final int token = generateToken();
1854 prepareOperationTimeout(token, TIMEOUT_SHARED_BACKUP_INTERVAL);
Christopher Tate79ec80d2011-06-24 14:58:49 -07001855 agent.doFullBackup(mOutputFile, token, mBackupManagerBinder);
Christopher Tateb0628bf2011-06-02 15:08:13 -07001856 if (!waitUntilOperationComplete(token)) {
1857 Slog.e(TAG, "Full backup failed on shared storage");
1858 } else {
1859 if (DEBUG) Slog.d(TAG, "Full shared storage backup success");
1860 }
1861 } else {
1862 Slog.e(TAG, "Could not bind to shared storage backup agent");
1863 }
1864 } catch (NameNotFoundException e) {
1865 Slog.e(TAG, "Shared storage backup package not found");
1866 } finally {
1867 tearDown(pkg);
1868 }
1869 }
1870
Christopher Tate4a627c72011-04-01 14:43:32 -07001871 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
1872 throws IOException {
1873 // Manifest format. All data are strings ending in LF:
1874 // BACKUP_MANIFEST_VERSION, currently 1
1875 //
1876 // Version 1:
1877 // package name
1878 // package's versionCode
Christopher Tate75a99702011-05-18 16:28:19 -07001879 // platform versionCode
1880 // getInstallerPackageName() for this package (maybe empty)
1881 // boolean: "1" if archive includes .apk; any other string means not
Christopher Tate4a627c72011-04-01 14:43:32 -07001882 // number of signatures == N
1883 // N*: signature byte array in ascii format per Signature.toCharsString()
1884 StringBuilder builder = new StringBuilder(4096);
1885 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
1886
1887 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
1888 printer.println(pkg.packageName);
1889 printer.println(Integer.toString(pkg.versionCode));
Christopher Tate75a99702011-05-18 16:28:19 -07001890 printer.println(Integer.toString(Build.VERSION.SDK_INT));
1891
1892 String installerName = mPackageManager.getInstallerPackageName(pkg.packageName);
1893 printer.println((installerName != null) ? installerName : "");
1894
Christopher Tate4a627c72011-04-01 14:43:32 -07001895 printer.println(withApk ? "1" : "0");
1896 if (pkg.signatures == null) {
1897 printer.println("0");
1898 } else {
1899 printer.println(Integer.toString(pkg.signatures.length));
1900 for (Signature sig : pkg.signatures) {
1901 printer.println(sig.toCharsString());
1902 }
1903 }
1904
1905 FileOutputStream outstream = new FileOutputStream(manifestFile);
Christopher Tate4a627c72011-04-01 14:43:32 -07001906 outstream.write(builder.toString().getBytes());
1907 outstream.close();
1908 }
1909
1910 private void tearDown(PackageInfo pkg) {
Christopher Tateb0628bf2011-06-02 15:08:13 -07001911 if (pkg != null) {
1912 final ApplicationInfo app = pkg.applicationInfo;
1913 if (app != null) {
1914 try {
1915 // unbind and tidy up even on timeout or failure, just in case
1916 mActivityManager.unbindBackupAgent(app);
Christopher Tate4a627c72011-04-01 14:43:32 -07001917
Christopher Tateb0628bf2011-06-02 15:08:13 -07001918 // The agent was running with a stub Application object, so shut it down.
1919 if (app.uid != Process.SYSTEM_UID) {
1920 if (DEBUG) Slog.d(TAG, "Backup complete, killing host process");
1921 mActivityManager.killApplicationProcess(app.processName, app.uid);
1922 } else {
1923 if (DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
1924 }
1925 } catch (RemoteException e) {
1926 Slog.d(TAG, "Lost app trying to shut down");
1927 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001928 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001929 }
1930 }
1931
1932 // wrappers for observer use
1933 void sendStartBackup() {
1934 if (mObserver != null) {
1935 try {
1936 mObserver.onStartBackup();
1937 } catch (RemoteException e) {
1938 Slog.w(TAG, "full backup observer went away: startBackup");
1939 mObserver = null;
1940 }
1941 }
1942 }
1943
1944 void sendOnBackupPackage(String name) {
1945 if (mObserver != null) {
1946 try {
1947 // TODO: use a more user-friendly name string
1948 mObserver.onBackupPackage(name);
1949 } catch (RemoteException e) {
1950 Slog.w(TAG, "full backup observer went away: backupPackage");
1951 mObserver = null;
1952 }
1953 }
1954 }
1955
1956 void sendEndBackup() {
1957 if (mObserver != null) {
1958 try {
1959 mObserver.onEndBackup();
1960 } catch (RemoteException e) {
1961 Slog.w(TAG, "full backup observer went away: endBackup");
1962 mObserver = null;
1963 }
1964 }
1965 }
1966 }
1967
1968
Christopher Tate75a99702011-05-18 16:28:19 -07001969 // ----- Full restore from a file/socket -----
1970
1971 // Description of a file in the restore datastream
1972 static class FileMetadata {
1973 String packageName; // name of the owning app
1974 String installerPackageName; // name of the market-type app that installed the owner
Christopher Tate79ec80d2011-06-24 14:58:49 -07001975 int type; // e.g. BackupAgent.TYPE_DIRECTORY
Christopher Tate75a99702011-05-18 16:28:19 -07001976 String domain; // e.g. FullBackup.DATABASE_TREE_TOKEN
1977 String path; // subpath within the semantic domain
1978 long mode; // e.g. 0666 (actually int)
1979 long mtime; // last mod time, UTC time_t (actually int)
1980 long size; // bytes of content
Christopher Tatee9e78ec2011-06-08 20:09:31 -07001981
1982 @Override
1983 public String toString() {
1984 StringBuilder sb = new StringBuilder(128);
1985 sb.append("FileMetadata{");
1986 sb.append(packageName); sb.append(',');
1987 sb.append(type); sb.append(',');
1988 sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
1989 sb.append(size);
1990 sb.append('}');
1991 return sb.toString();
1992 }
Christopher Tate75a99702011-05-18 16:28:19 -07001993 }
1994
1995 enum RestorePolicy {
1996 IGNORE,
1997 ACCEPT,
1998 ACCEPT_IF_APK
1999 }
2000
2001 class PerformFullRestoreTask implements Runnable {
2002 ParcelFileDescriptor mInputFile;
2003 IFullBackupRestoreObserver mObserver;
2004 AtomicBoolean mLatchObject;
2005 IBackupAgent mAgent;
2006 String mAgentPackage;
2007 ApplicationInfo mTargetApp;
2008 ParcelFileDescriptor[] mPipes = null;
2009
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002010 long mBytes;
2011
Christopher Tate75a99702011-05-18 16:28:19 -07002012 // possible handling states for a given package in the restore dataset
2013 final HashMap<String, RestorePolicy> mPackagePolicies
2014 = new HashMap<String, RestorePolicy>();
2015
2016 // installer package names for each encountered app, derived from the manifests
2017 final HashMap<String, String> mPackageInstallers = new HashMap<String, String>();
2018
2019 // Signatures for a given package found in its manifest file
2020 final HashMap<String, Signature[]> mManifestSignatures
2021 = new HashMap<String, Signature[]>();
2022
2023 // Packages we've already wiped data on when restoring their first file
2024 final HashSet<String> mClearedPackages = new HashSet<String>();
2025
2026 PerformFullRestoreTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
2027 AtomicBoolean latch) {
2028 mInputFile = fd;
2029 mObserver = observer;
2030 mLatchObject = latch;
2031 mAgent = null;
2032 mAgentPackage = null;
2033 mTargetApp = null;
2034
2035 // Which packages we've already wiped data on. We prepopulate this
2036 // with a whitelist of packages known to be unclearable.
2037 mClearedPackages.add("android");
Christopher Tate75a99702011-05-18 16:28:19 -07002038 mClearedPackages.add("com.android.providers.settings");
Christopher Tateb0628bf2011-06-02 15:08:13 -07002039
Christopher Tate75a99702011-05-18 16:28:19 -07002040 }
2041
2042 class RestoreFileRunnable implements Runnable {
2043 IBackupAgent mAgent;
2044 FileMetadata mInfo;
2045 ParcelFileDescriptor mSocket;
2046 int mToken;
2047
2048 RestoreFileRunnable(IBackupAgent agent, FileMetadata info,
2049 ParcelFileDescriptor socket, int token) throws IOException {
2050 mAgent = agent;
2051 mInfo = info;
2052 mToken = token;
2053
2054 // This class is used strictly for process-local binder invocations. The
2055 // semantics of ParcelFileDescriptor differ in this case; in particular, we
2056 // do not automatically get a 'dup'ed descriptor that we can can continue
2057 // to use asynchronously from the caller. So, we make sure to dup it ourselves
2058 // before proceeding to do the restore.
2059 mSocket = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2060 }
2061
2062 @Override
2063 public void run() {
2064 try {
2065 mAgent.doRestoreFile(mSocket, mInfo.size, mInfo.type,
2066 mInfo.domain, mInfo.path, mInfo.mode, mInfo.mtime,
2067 mToken, mBackupManagerBinder);
2068 } catch (RemoteException e) {
2069 // never happens; this is used strictly for local binder calls
2070 }
2071 }
2072 }
2073
2074 @Override
2075 public void run() {
2076 Slog.i(TAG, "--- Performing full-dataset restore ---");
2077 sendStartRestore();
2078
Christopher Tateb0628bf2011-06-02 15:08:13 -07002079 // Are we able to restore shared-storage data?
2080 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
2081 mPackagePolicies.put("com.android.sharedstoragebackup", RestorePolicy.ACCEPT);
2082 }
2083
Christopher Tate75a99702011-05-18 16:28:19 -07002084 try {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002085 mBytes = 0;
Christopher Tate75a99702011-05-18 16:28:19 -07002086 byte[] buffer = new byte[32 * 1024];
2087 FileInputStream instream = new FileInputStream(mInputFile.getFileDescriptor());
2088
2089 boolean didRestore;
2090 do {
2091 didRestore = restoreOneFile(instream, buffer);
2092 } while (didRestore);
2093
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002094 if (DEBUG) Slog.v(TAG, "Done consuming input tarfile, total bytes=" + mBytes);
Christopher Tate75a99702011-05-18 16:28:19 -07002095 } finally {
2096 tearDownPipes();
2097 tearDownAgent(mTargetApp);
2098
2099 try {
2100 mInputFile.close();
2101 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002102 Slog.w(TAG, "Close of restore data pipe threw", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002103 /* nothing we can do about this */
2104 }
2105 synchronized (mCurrentOpLock) {
2106 mCurrentOperations.clear();
2107 }
2108 synchronized (mLatchObject) {
2109 mLatchObject.set(true);
2110 mLatchObject.notifyAll();
2111 }
2112 sendEndRestore();
2113 mWakelock.release();
2114 if (DEBUG) Slog.d(TAG, "Full restore pass complete.");
2115 }
2116 }
2117
2118 boolean restoreOneFile(InputStream instream, byte[] buffer) {
2119 FileMetadata info;
2120 try {
2121 info = readTarHeaders(instream);
2122 if (info != null) {
2123 if (DEBUG) {
2124 dumpFileMetadata(info);
2125 }
2126
2127 final String pkg = info.packageName;
2128 if (!pkg.equals(mAgentPackage)) {
2129 // okay, change in package; set up our various
2130 // bookkeeping if we haven't seen it yet
2131 if (!mPackagePolicies.containsKey(pkg)) {
2132 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2133 }
2134
2135 // Clean up the previous agent relationship if necessary,
2136 // and let the observer know we're considering a new app.
2137 if (mAgent != null) {
2138 if (DEBUG) Slog.d(TAG, "Saw new package; tearing down old one");
2139 tearDownPipes();
2140 tearDownAgent(mTargetApp);
2141 mTargetApp = null;
2142 mAgentPackage = null;
2143 }
2144 }
2145
2146 if (info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2147 mPackagePolicies.put(pkg, readAppManifest(info, instream));
2148 mPackageInstallers.put(pkg, info.installerPackageName);
2149 // We've read only the manifest content itself at this point,
2150 // so consume the footer before looping around to the next
2151 // input file
2152 skipTarPadding(info.size, instream);
2153 sendOnRestorePackage(pkg);
2154 } else {
2155 // Non-manifest, so it's actual file data. Is this a package
2156 // we're ignoring?
2157 boolean okay = true;
2158 RestorePolicy policy = mPackagePolicies.get(pkg);
2159 switch (policy) {
2160 case IGNORE:
2161 okay = false;
2162 break;
2163
2164 case ACCEPT_IF_APK:
2165 // If we're in accept-if-apk state, then the first file we
2166 // see MUST be the apk.
2167 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2168 if (DEBUG) Slog.d(TAG, "APK file; installing");
2169 // Try to install the app.
2170 String installerName = mPackageInstallers.get(pkg);
2171 okay = installApk(info, installerName, instream);
2172 // good to go; promote to ACCEPT
2173 mPackagePolicies.put(pkg, (okay)
2174 ? RestorePolicy.ACCEPT
2175 : RestorePolicy.IGNORE);
2176 // At this point we've consumed this file entry
2177 // ourselves, so just strip the tar footer and
2178 // go on to the next file in the input stream
2179 skipTarPadding(info.size, instream);
2180 return true;
2181 } else {
2182 // File data before (or without) the apk. We can't
2183 // handle it coherently in this case so ignore it.
2184 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2185 okay = false;
2186 }
2187 break;
2188
2189 case ACCEPT:
2190 if (info.domain.equals(FullBackup.APK_TREE_TOKEN)) {
2191 if (DEBUG) Slog.d(TAG, "apk present but ACCEPT");
2192 // we can take the data without the apk, so we
2193 // *want* to do so. skip the apk by declaring this
2194 // one file not-okay without changing the restore
2195 // policy for the package.
2196 okay = false;
2197 }
2198 break;
2199
2200 default:
2201 // Something has gone dreadfully wrong when determining
2202 // the restore policy from the manifest. Ignore the
2203 // rest of this package's data.
2204 Slog.e(TAG, "Invalid policy from manifest");
2205 okay = false;
2206 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2207 break;
2208 }
2209
2210 // If the policy is satisfied, go ahead and set up to pipe the
2211 // data to the agent.
2212 if (DEBUG && okay && mAgent != null) {
2213 Slog.i(TAG, "Reusing existing agent instance");
2214 }
2215 if (okay && mAgent == null) {
2216 if (DEBUG) Slog.d(TAG, "Need to launch agent for " + pkg);
2217
2218 try {
2219 mTargetApp = mPackageManager.getApplicationInfo(pkg, 0);
2220
2221 // If we haven't sent any data to this app yet, we probably
2222 // need to clear it first. Check that.
2223 if (!mClearedPackages.contains(pkg)) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002224 // apps with their own backup agents are
Christopher Tate75a99702011-05-18 16:28:19 -07002225 // responsible for coherently managing a full
2226 // restore.
Christopher Tate79ec80d2011-06-24 14:58:49 -07002227 if (mTargetApp.backupAgentName == null) {
Christopher Tate75a99702011-05-18 16:28:19 -07002228 if (DEBUG) Slog.d(TAG, "Clearing app data preparatory to full restore");
2229 clearApplicationDataSynchronous(pkg);
2230 } else {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002231 if (DEBUG) Slog.d(TAG, "backup agent ("
2232 + mTargetApp.backupAgentName + ") => no clear");
Christopher Tate75a99702011-05-18 16:28:19 -07002233 }
2234 mClearedPackages.add(pkg);
2235 } else {
2236 if (DEBUG) Slog.d(TAG, "We've initialized this app already; no clear required");
2237 }
2238
2239 // All set; now set up the IPC and launch the agent
2240 setUpPipes();
2241 mAgent = bindToAgentSynchronous(mTargetApp,
2242 IApplicationThread.BACKUP_MODE_RESTORE_FULL);
2243 mAgentPackage = pkg;
2244 } catch (IOException e) {
2245 // fall through to error handling
2246 } catch (NameNotFoundException e) {
2247 // fall through to error handling
2248 }
2249
2250 if (mAgent == null) {
2251 if (DEBUG) Slog.d(TAG, "Unable to create agent for " + pkg);
2252 okay = false;
2253 tearDownPipes();
2254 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2255 }
2256 }
2257
2258 // Sanity check: make sure we never give data to the wrong app. This
2259 // should never happen but a little paranoia here won't go amiss.
2260 if (okay && !pkg.equals(mAgentPackage)) {
2261 Slog.e(TAG, "Restoring data for " + pkg
2262 + " but agent is for " + mAgentPackage);
2263 okay = false;
2264 }
2265
2266 // At this point we have an agent ready to handle the full
2267 // restore data as well as a pipe for sending data to
2268 // that agent. Tell the agent to start reading from the
2269 // pipe.
2270 if (okay) {
2271 boolean agentSuccess = true;
2272 long toCopy = info.size;
2273 final int token = generateToken();
2274 try {
2275 if (DEBUG) Slog.d(TAG, "Invoking agent to restore file "
2276 + info.path);
2277 prepareOperationTimeout(token,
2278 TIMEOUT_FULL_BACKUP_INTERVAL);
2279 // fire up the app's agent listening on the socket. If
2280 // the agent is running in the system process we can't
2281 // just invoke it asynchronously, so we provide a thread
2282 // for it here.
2283 if (mTargetApp.processName.equals("system")) {
2284 Slog.d(TAG, "system process agent - spinning a thread");
2285 RestoreFileRunnable runner = new RestoreFileRunnable(
2286 mAgent, info, mPipes[0], token);
2287 new Thread(runner).start();
2288 } else {
2289 mAgent.doRestoreFile(mPipes[0], info.size, info.type,
2290 info.domain, info.path, info.mode, info.mtime,
2291 token, mBackupManagerBinder);
2292 }
2293 } catch (IOException e) {
2294 // couldn't dup the socket for a process-local restore
2295 Slog.d(TAG, "Couldn't establish restore");
2296 agentSuccess = false;
2297 okay = false;
2298 } catch (RemoteException e) {
2299 // whoops, remote agent went away. We'll eat the content
2300 // ourselves, then, and not copy it over.
2301 Slog.e(TAG, "Agent crashed during full restore");
2302 agentSuccess = false;
2303 okay = false;
2304 }
2305
2306 // Copy over the data if the agent is still good
2307 if (okay) {
2308 boolean pipeOkay = true;
2309 FileOutputStream pipe = new FileOutputStream(
2310 mPipes[1].getFileDescriptor());
2311 if (DEBUG) Slog.d(TAG, "Piping data to agent");
2312 while (toCopy > 0) {
2313 int toRead = (toCopy > buffer.length)
2314 ? buffer.length : (int)toCopy;
2315 int nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002316 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002317 if (nRead <= 0) break;
2318 toCopy -= nRead;
2319
2320 // send it to the output pipe as long as things
2321 // are still good
2322 if (pipeOkay) {
2323 try {
2324 pipe.write(buffer, 0, nRead);
2325 } catch (IOException e) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002326 Slog.e(TAG, "Failed to write to restore pipe", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002327 pipeOkay = false;
2328 }
2329 }
2330 }
2331
2332 // done sending that file! Now we just need to consume
2333 // the delta from info.size to the end of block.
2334 skipTarPadding(info.size, instream);
2335
2336 // and now that we've sent it all, wait for the remote
2337 // side to acknowledge receipt
2338 agentSuccess = waitUntilOperationComplete(token);
2339 }
2340
2341 // okay, if the remote end failed at any point, deal with
2342 // it by ignoring the rest of the restore on it
2343 if (!agentSuccess) {
2344 mBackupHandler.removeMessages(MSG_TIMEOUT);
2345 tearDownPipes();
2346 tearDownAgent(mTargetApp);
2347 mAgent = null;
2348 mPackagePolicies.put(pkg, RestorePolicy.IGNORE);
2349 }
2350 }
2351
2352 // Problems setting up the agent communication, or an already-
2353 // ignored package: skip to the next tar stream entry by
2354 // reading and discarding this file.
2355 if (!okay) {
2356 if (DEBUG) Slog.d(TAG, "[discarding file content]");
2357 long bytesToConsume = (info.size + 511) & ~511;
2358 while (bytesToConsume > 0) {
2359 int toRead = (bytesToConsume > buffer.length)
2360 ? buffer.length : (int)bytesToConsume;
2361 long nRead = instream.read(buffer, 0, toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002362 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002363 if (nRead <= 0) break;
2364 bytesToConsume -= nRead;
2365 }
2366 }
2367 }
2368 }
2369 } catch (IOException e) {
2370 Slog.w(TAG, "io exception on restore socket read", e);
2371 // treat as EOF
2372 info = null;
2373 }
2374
2375 return (info != null);
2376 }
2377
2378 void setUpPipes() throws IOException {
2379 mPipes = ParcelFileDescriptor.createPipe();
2380 }
2381
2382 void tearDownPipes() {
2383 if (mPipes != null) {
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002384 try {
2385 mPipes[0].close();
2386 mPipes[0] = null;
2387 mPipes[1].close();
2388 mPipes[1] = null;
2389 } catch (IOException e) {
2390 Slog.w(TAG, "Couldn't close agent pipes", e);
Christopher Tate75a99702011-05-18 16:28:19 -07002391 }
2392 mPipes = null;
2393 }
2394 }
2395
2396 void tearDownAgent(ApplicationInfo app) {
2397 if (mAgent != null) {
2398 try {
2399 // unbind and tidy up even on timeout or failure, just in case
2400 mActivityManager.unbindBackupAgent(app);
2401
2402 // The agent was running with a stub Application object, so shut it down.
2403 // !!! We hardcode the confirmation UI's package name here rather than use a
2404 // manifest flag! TODO something less direct.
2405 if (app.uid != Process.SYSTEM_UID
2406 && !app.packageName.equals("com.android.backupconfirm")) {
2407 if (DEBUG) Slog.d(TAG, "Killing host process");
2408 mActivityManager.killApplicationProcess(app.processName, app.uid);
2409 } else {
2410 if (DEBUG) Slog.d(TAG, "Not killing after full restore");
2411 }
2412 } catch (RemoteException e) {
2413 Slog.d(TAG, "Lost app trying to shut down");
2414 }
2415 mAgent = null;
2416 }
2417 }
2418
2419 class RestoreInstallObserver extends IPackageInstallObserver.Stub {
2420 final AtomicBoolean mDone = new AtomicBoolean();
Christopher Tatea858cb02011-06-03 12:27:51 -07002421 String mPackageName;
Christopher Tate75a99702011-05-18 16:28:19 -07002422 int mResult;
2423
2424 public void reset() {
2425 synchronized (mDone) {
2426 mDone.set(false);
2427 }
2428 }
2429
2430 public void waitForCompletion() {
2431 synchronized (mDone) {
2432 while (mDone.get() == false) {
2433 try {
2434 mDone.wait();
2435 } catch (InterruptedException e) { }
2436 }
2437 }
2438 }
2439
2440 int getResult() {
2441 return mResult;
2442 }
2443
2444 @Override
2445 public void packageInstalled(String packageName, int returnCode)
2446 throws RemoteException {
2447 synchronized (mDone) {
2448 mResult = returnCode;
Christopher Tatea858cb02011-06-03 12:27:51 -07002449 mPackageName = packageName;
Christopher Tate75a99702011-05-18 16:28:19 -07002450 mDone.set(true);
2451 mDone.notifyAll();
2452 }
2453 }
2454 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002455
2456 class RestoreDeleteObserver extends IPackageDeleteObserver.Stub {
2457 final AtomicBoolean mDone = new AtomicBoolean();
2458 int mResult;
2459
2460 public void reset() {
2461 synchronized (mDone) {
2462 mDone.set(false);
2463 }
2464 }
2465
2466 public void waitForCompletion() {
2467 synchronized (mDone) {
2468 while (mDone.get() == false) {
2469 try {
2470 mDone.wait();
2471 } catch (InterruptedException e) { }
2472 }
2473 }
2474 }
2475
2476 @Override
2477 public void packageDeleted(String packageName, int returnCode) throws RemoteException {
2478 synchronized (mDone) {
2479 mResult = returnCode;
2480 mDone.set(true);
2481 mDone.notifyAll();
2482 }
2483 }
2484 }
2485
Christopher Tate75a99702011-05-18 16:28:19 -07002486 final RestoreInstallObserver mInstallObserver = new RestoreInstallObserver();
Christopher Tatea858cb02011-06-03 12:27:51 -07002487 final RestoreDeleteObserver mDeleteObserver = new RestoreDeleteObserver();
Christopher Tate75a99702011-05-18 16:28:19 -07002488
2489 boolean installApk(FileMetadata info, String installerPackage, InputStream instream) {
2490 boolean okay = true;
2491
2492 if (DEBUG) Slog.d(TAG, "Installing from backup: " + info.packageName);
2493
2494 // The file content is an .apk file. Copy it out to a staging location and
2495 // attempt to install it.
2496 File apkFile = new File(mDataDir, info.packageName);
2497 try {
2498 FileOutputStream apkStream = new FileOutputStream(apkFile);
2499 byte[] buffer = new byte[32 * 1024];
2500 long size = info.size;
2501 while (size > 0) {
2502 long toRead = (buffer.length < size) ? buffer.length : size;
2503 int didRead = instream.read(buffer, 0, (int)toRead);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002504 if (didRead >= 0) mBytes += didRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002505 apkStream.write(buffer, 0, didRead);
2506 size -= didRead;
2507 }
2508 apkStream.close();
2509
2510 // make sure the installer can read it
2511 apkFile.setReadable(true, false);
2512
2513 // Now install it
2514 Uri packageUri = Uri.fromFile(apkFile);
2515 mInstallObserver.reset();
2516 mPackageManager.installPackage(packageUri, mInstallObserver,
2517 PackageManager.INSTALL_REPLACE_EXISTING, installerPackage);
2518 mInstallObserver.waitForCompletion();
2519
2520 if (mInstallObserver.getResult() != PackageManager.INSTALL_SUCCEEDED) {
2521 // The only time we continue to accept install of data even if the
2522 // apk install failed is if we had already determined that we could
2523 // accept the data regardless.
2524 if (mPackagePolicies.get(info.packageName) != RestorePolicy.ACCEPT) {
2525 okay = false;
2526 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002527 } else {
2528 // Okay, the install succeeded. Make sure it was the right app.
2529 boolean uninstall = false;
2530 if (!mInstallObserver.mPackageName.equals(info.packageName)) {
2531 Slog.w(TAG, "Restore stream claimed to include apk for "
2532 + info.packageName + " but apk was really "
2533 + mInstallObserver.mPackageName);
2534 // delete the package we just put in place; it might be fraudulent
2535 okay = false;
2536 uninstall = true;
2537 } else {
2538 try {
2539 PackageInfo pkg = mPackageManager.getPackageInfo(info.packageName,
2540 PackageManager.GET_SIGNATURES);
2541 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) == 0) {
2542 Slog.w(TAG, "Restore stream contains apk of package "
2543 + info.packageName + " but it disallows backup/restore");
2544 okay = false;
2545 } else {
2546 // So far so good -- do the signatures match the manifest?
2547 Signature[] sigs = mManifestSignatures.get(info.packageName);
2548 if (!signaturesMatch(sigs, pkg)) {
2549 Slog.w(TAG, "Installed app " + info.packageName
2550 + " signatures do not match restore manifest");
2551 okay = false;
2552 uninstall = true;
2553 }
2554 }
2555 } catch (NameNotFoundException e) {
2556 Slog.w(TAG, "Install of package " + info.packageName
2557 + " succeeded but now not found");
2558 okay = false;
2559 }
2560 }
2561
2562 // If we're not okay at this point, we need to delete the package
2563 // that we just installed.
2564 if (uninstall) {
2565 mDeleteObserver.reset();
2566 mPackageManager.deletePackage(mInstallObserver.mPackageName,
2567 mDeleteObserver, 0);
2568 mDeleteObserver.waitForCompletion();
2569 }
Christopher Tate75a99702011-05-18 16:28:19 -07002570 }
2571 } catch (IOException e) {
2572 Slog.e(TAG, "Unable to transcribe restored apk for install");
2573 okay = false;
2574 } finally {
2575 apkFile.delete();
2576 }
2577
2578 return okay;
2579 }
2580
2581 // Given an actual file content size, consume the post-content padding mandated
2582 // by the tar format.
2583 void skipTarPadding(long size, InputStream instream) throws IOException {
2584 long partial = (size + 512) % 512;
2585 if (partial > 0) {
2586 byte[] buffer = new byte[512];
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002587 int nRead = instream.read(buffer, 0, 512 - (int)partial);
2588 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002589 }
2590 }
2591
2592 // Returns a policy constant; takes a buffer arg to reduce memory churn
2593 RestorePolicy readAppManifest(FileMetadata info, InputStream instream)
2594 throws IOException {
2595 // Fail on suspiciously large manifest files
2596 if (info.size > 64 * 1024) {
2597 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
2598 }
2599 byte[] buffer = new byte[(int) info.size];
2600 int nRead = 0;
2601 while (nRead < info.size) {
2602 nRead += instream.read(buffer, nRead, (int)info.size - nRead);
2603 }
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002604 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002605
2606 RestorePolicy policy = RestorePolicy.IGNORE;
2607 String[] str = new String[1];
2608 int offset = 0;
2609
2610 try {
2611 offset = extractLine(buffer, offset, str);
2612 int version = Integer.parseInt(str[0]);
2613 if (version == BACKUP_MANIFEST_VERSION) {
2614 offset = extractLine(buffer, offset, str);
2615 String manifestPackage = str[0];
2616 // TODO: handle <original-package>
2617 if (manifestPackage.equals(info.packageName)) {
2618 offset = extractLine(buffer, offset, str);
2619 version = Integer.parseInt(str[0]); // app version
2620 offset = extractLine(buffer, offset, str);
2621 int platformVersion = Integer.parseInt(str[0]);
2622 offset = extractLine(buffer, offset, str);
2623 info.installerPackageName = (str[0].length() > 0) ? str[0] : null;
2624 offset = extractLine(buffer, offset, str);
2625 boolean hasApk = str[0].equals("1");
2626 offset = extractLine(buffer, offset, str);
2627 int numSigs = Integer.parseInt(str[0]);
Christopher Tate75a99702011-05-18 16:28:19 -07002628 if (numSigs > 0) {
Christopher Tatea858cb02011-06-03 12:27:51 -07002629 Signature[] sigs = new Signature[numSigs];
Christopher Tate75a99702011-05-18 16:28:19 -07002630 for (int i = 0; i < numSigs; i++) {
2631 offset = extractLine(buffer, offset, str);
2632 sigs[i] = new Signature(str[0]);
2633 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002634 mManifestSignatures.put(info.packageName, sigs);
Christopher Tate75a99702011-05-18 16:28:19 -07002635
2636 // Okay, got the manifest info we need...
2637 try {
Christopher Tate75a99702011-05-18 16:28:19 -07002638 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2639 info.packageName, PackageManager.GET_SIGNATURES);
Christopher Tatea858cb02011-06-03 12:27:51 -07002640 // Fall through to IGNORE if the app explicitly disallows backup
2641 final int flags = pkgInfo.applicationInfo.flags;
2642 if ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
2643 // Verify signatures against any installed version; if they
2644 // don't match, then we fall though and ignore the data. The
2645 // signatureMatch() method explicitly ignores the signature
2646 // check for packages installed on the system partition, because
2647 // such packages are signed with the platform cert instead of
2648 // the app developer's cert, so they're different on every
2649 // device.
2650 if (signaturesMatch(sigs, pkgInfo)) {
2651 if (pkgInfo.versionCode >= version) {
2652 Slog.i(TAG, "Sig + version match; taking data");
2653 policy = RestorePolicy.ACCEPT;
2654 } else {
2655 // The data is from a newer version of the app than
2656 // is presently installed. That means we can only
2657 // use it if the matching apk is also supplied.
2658 Slog.d(TAG, "Data version " + version
2659 + " is newer than installed version "
2660 + pkgInfo.versionCode + " - requiring apk");
2661 policy = RestorePolicy.ACCEPT_IF_APK;
2662 }
Christopher Tate75a99702011-05-18 16:28:19 -07002663 } else {
Christopher Tatea858cb02011-06-03 12:27:51 -07002664 Slog.w(TAG, "Restore manifest signatures do not match "
2665 + "installed application for " + info.packageName);
Christopher Tate75a99702011-05-18 16:28:19 -07002666 }
Christopher Tatea858cb02011-06-03 12:27:51 -07002667 } else {
2668 if (DEBUG) Slog.i(TAG, "Restore manifest from "
2669 + info.packageName + " but allowBackup=false");
Christopher Tate75a99702011-05-18 16:28:19 -07002670 }
2671 } catch (NameNotFoundException e) {
2672 // Okay, the target app isn't installed. We can process
2673 // the restore properly only if the dataset provides the
2674 // apk file and we can successfully install it.
2675 if (DEBUG) Slog.i(TAG, "Package " + info.packageName
2676 + " not installed; requiring apk in dataset");
2677 policy = RestorePolicy.ACCEPT_IF_APK;
2678 }
2679
2680 if (policy == RestorePolicy.ACCEPT_IF_APK && !hasApk) {
2681 Slog.i(TAG, "Cannot restore package " + info.packageName
2682 + " without the matching .apk");
2683 }
2684 } else {
2685 Slog.i(TAG, "Missing signature on backed-up package "
2686 + info.packageName);
2687 }
2688 } else {
2689 Slog.i(TAG, "Expected package " + info.packageName
2690 + " but restore manifest claims " + manifestPackage);
2691 }
2692 } else {
2693 Slog.i(TAG, "Unknown restore manifest version " + version
2694 + " for package " + info.packageName);
2695 }
2696 } catch (NumberFormatException e) {
2697 Slog.w(TAG, "Corrupt restore manifest for package " + info.packageName);
2698 }
2699
2700 return policy;
2701 }
2702
2703 // Builds a line from a byte buffer starting at 'offset', and returns
2704 // the index of the next unconsumed data in the buffer.
2705 int extractLine(byte[] buffer, int offset, String[] outStr) throws IOException {
2706 final int end = buffer.length;
2707 if (offset >= end) throw new IOException("Incomplete data");
2708
2709 int pos;
2710 for (pos = offset; pos < end; pos++) {
2711 byte c = buffer[pos];
2712 // at LF we declare end of line, and return the next char as the
2713 // starting point for the next time through
2714 if (c == '\n') {
2715 break;
2716 }
2717 }
2718 outStr[0] = new String(buffer, offset, pos - offset);
2719 pos++; // may be pointing an extra byte past the end but that's okay
2720 return pos;
2721 }
2722
2723 void dumpFileMetadata(FileMetadata info) {
2724 if (DEBUG) {
2725 StringBuilder b = new StringBuilder(128);
2726
2727 // mode string
Christopher Tate79ec80d2011-06-24 14:58:49 -07002728 b.append((info.type == BackupAgent.TYPE_DIRECTORY) ? 'd' : '-');
Christopher Tate75a99702011-05-18 16:28:19 -07002729 b.append(((info.mode & 0400) != 0) ? 'r' : '-');
2730 b.append(((info.mode & 0200) != 0) ? 'w' : '-');
2731 b.append(((info.mode & 0100) != 0) ? 'x' : '-');
2732 b.append(((info.mode & 0040) != 0) ? 'r' : '-');
2733 b.append(((info.mode & 0020) != 0) ? 'w' : '-');
2734 b.append(((info.mode & 0010) != 0) ? 'x' : '-');
2735 b.append(((info.mode & 0004) != 0) ? 'r' : '-');
2736 b.append(((info.mode & 0002) != 0) ? 'w' : '-');
2737 b.append(((info.mode & 0001) != 0) ? 'x' : '-');
2738 b.append(String.format(" %9d ", info.size));
2739
2740 Date stamp = new Date(info.mtime);
2741 b.append(new SimpleDateFormat("MMM dd kk:mm:ss ").format(stamp));
2742
2743 b.append(info.packageName);
2744 b.append(" :: ");
2745 b.append(info.domain);
2746 b.append(" :: ");
2747 b.append(info.path);
2748
2749 Slog.i(TAG, b.toString());
2750 }
2751 }
2752 // Consume a tar file header block [sequence] and accumulate the relevant metadata
2753 FileMetadata readTarHeaders(InputStream instream) throws IOException {
2754 byte[] block = new byte[512];
2755 FileMetadata info = null;
2756
2757 boolean gotHeader = readTarHeader(instream, block);
2758 if (gotHeader) {
2759 // okay, presume we're okay, and extract the various metadata
2760 info = new FileMetadata();
2761 info.size = extractRadix(block, 124, 12, 8);
2762 info.mtime = extractRadix(block, 136, 12, 8);
2763 info.mode = extractRadix(block, 100, 8, 8);
2764
2765 info.path = extractString(block, 345, 155); // prefix
2766 String path = extractString(block, 0, 100);
2767 if (path.length() > 0) {
2768 if (info.path.length() > 0) info.path += '/';
2769 info.path += path;
2770 }
2771
2772 // tar link indicator field: 1 byte at offset 156 in the header.
2773 int typeChar = block[156];
2774 if (typeChar == 'x') {
2775 // pax extended header, so we need to read that
2776 gotHeader = readPaxExtendedHeader(instream, info);
2777 if (gotHeader) {
2778 // and after a pax extended header comes another real header -- read
2779 // that to find the real file type
2780 gotHeader = readTarHeader(instream, block);
2781 }
2782 if (!gotHeader) throw new IOException("Bad or missing pax header");
2783
2784 typeChar = block[156];
2785 }
2786
2787 switch (typeChar) {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002788 case '0': info.type = BackupAgent.TYPE_FILE; break;
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002789 case '5': {
Christopher Tate79ec80d2011-06-24 14:58:49 -07002790 info.type = BackupAgent.TYPE_DIRECTORY;
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002791 if (info.size != 0) {
2792 Slog.w(TAG, "Directory entry with nonzero size in header");
2793 info.size = 0;
2794 }
2795 break;
2796 }
Christopher Tate75a99702011-05-18 16:28:19 -07002797 case 0: {
2798 // presume EOF
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002799 if (DEBUG) Slog.w(TAG, "Saw type=0 in tar header block, info=" + info);
Christopher Tate75a99702011-05-18 16:28:19 -07002800 return null;
2801 }
2802 default: {
2803 Slog.e(TAG, "Unknown tar entity type: " + typeChar);
2804 throw new IOException("Unknown entity type " + typeChar);
2805 }
2806 }
2807
2808 // Parse out the path
2809 //
2810 // first: apps/shared/unrecognized
2811 if (FullBackup.SHARED_PREFIX.regionMatches(0,
2812 info.path, 0, FullBackup.SHARED_PREFIX.length())) {
2813 // File in shared storage. !!! TODO: implement this.
2814 info.path = info.path.substring(FullBackup.SHARED_PREFIX.length());
Christopher Tateb0628bf2011-06-02 15:08:13 -07002815 info.packageName = "com.android.sharedstoragebackup";
Christopher Tate75a99702011-05-18 16:28:19 -07002816 info.domain = FullBackup.SHARED_STORAGE_TOKEN;
Christopher Tateb0628bf2011-06-02 15:08:13 -07002817 if (DEBUG) Slog.i(TAG, "File in shared storage: " + info.path);
Christopher Tate75a99702011-05-18 16:28:19 -07002818 } else if (FullBackup.APPS_PREFIX.regionMatches(0,
2819 info.path, 0, FullBackup.APPS_PREFIX.length())) {
2820 // App content! Parse out the package name and domain
2821
2822 // strip the apps/ prefix
2823 info.path = info.path.substring(FullBackup.APPS_PREFIX.length());
2824
2825 // extract the package name
2826 int slash = info.path.indexOf('/');
2827 if (slash < 0) throw new IOException("Illegal semantic path in " + info.path);
2828 info.packageName = info.path.substring(0, slash);
2829 info.path = info.path.substring(slash+1);
2830
2831 // if it's a manifest we're done, otherwise parse out the domains
2832 if (!info.path.equals(BACKUP_MANIFEST_FILENAME)) {
2833 slash = info.path.indexOf('/');
2834 if (slash < 0) throw new IOException("Illegal semantic path in non-manifest " + info.path);
2835 info.domain = info.path.substring(0, slash);
2836 // validate that it's one of the domains we understand
2837 if (!info.domain.equals(FullBackup.APK_TREE_TOKEN)
2838 && !info.domain.equals(FullBackup.DATA_TREE_TOKEN)
2839 && !info.domain.equals(FullBackup.DATABASE_TREE_TOKEN)
2840 && !info.domain.equals(FullBackup.ROOT_TREE_TOKEN)
2841 && !info.domain.equals(FullBackup.SHAREDPREFS_TREE_TOKEN)
2842 && !info.domain.equals(FullBackup.OBB_TREE_TOKEN)
2843 && !info.domain.equals(FullBackup.CACHE_TREE_TOKEN)) {
2844 throw new IOException("Unrecognized domain " + info.domain);
2845 }
2846
2847 info.path = info.path.substring(slash + 1);
2848 }
2849 }
2850 }
2851 return info;
2852 }
2853
2854 boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
2855 int nRead = instream.read(block, 0, 512);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002856 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002857 if (nRead > 0 && nRead != 512) {
2858 // if we read only a partial block, then things are
2859 // clearly screwed up. terminate the restore.
2860 throw new IOException("Partial header block: " + nRead);
2861 }
2862 return (nRead > 0);
2863 }
2864
2865 // overwrites 'info' fields based on the pax extended header
2866 boolean readPaxExtendedHeader(InputStream instream, FileMetadata info)
2867 throws IOException {
2868 // We should never see a pax extended header larger than this
2869 if (info.size > 32*1024) {
2870 Slog.w(TAG, "Suspiciously large pax header size " + info.size
2871 + " - aborting");
2872 throw new IOException("Sanity failure: pax header size " + info.size);
2873 }
2874
2875 // read whole blocks, not just the content size
2876 int numBlocks = (int)((info.size + 511) >> 9);
2877 byte[] data = new byte[numBlocks * 512];
2878 int nRead = instream.read(data);
Christopher Tatee9e78ec2011-06-08 20:09:31 -07002879 if (nRead >= 0) mBytes += nRead;
Christopher Tate75a99702011-05-18 16:28:19 -07002880 if (nRead != data.length) {
2881 return false;
2882 }
2883
2884 final int contentSize = (int) info.size;
2885 int offset = 0;
2886 do {
2887 // extract the line at 'offset'
2888 int eol = offset+1;
2889 while (eol < contentSize && data[eol] != ' ') eol++;
2890 if (eol >= contentSize) {
2891 // error: we just hit EOD looking for the end of the size field
2892 throw new IOException("Invalid pax data");
2893 }
2894 // eol points to the space between the count and the key
2895 int linelen = (int) extractRadix(data, offset, eol - offset, 10);
2896 int key = eol + 1; // start of key=value
2897 eol = offset + linelen - 1; // trailing LF
2898 int value;
2899 for (value = key+1; data[value] != '=' && value <= eol; value++);
2900 if (value > eol) {
2901 throw new IOException("Invalid pax declaration");
2902 }
2903
2904 // pax requires that key/value strings be in UTF-8
2905 String keyStr = new String(data, key, value-key, "UTF-8");
2906 // -1 to strip the trailing LF
2907 String valStr = new String(data, value+1, eol-value-1, "UTF-8");
2908
2909 if ("path".equals(keyStr)) {
2910 info.path = valStr;
2911 } else if ("size".equals(keyStr)) {
2912 info.size = Long.parseLong(valStr);
2913 } else {
2914 if (DEBUG) Slog.i(TAG, "Unhandled pax key: " + key);
2915 }
2916
2917 offset += linelen;
2918 } while (offset < contentSize);
2919
2920 return true;
2921 }
2922
2923 long extractRadix(byte[] data, int offset, int maxChars, int radix)
2924 throws IOException {
2925 long value = 0;
2926 final int end = offset + maxChars;
2927 for (int i = offset; i < end; i++) {
2928 final byte b = data[i];
Christopher Tate3f6c77b2011-06-07 13:17:17 -07002929 // Numeric fields in tar can terminate with either NUL or SPC
Christopher Tate75a99702011-05-18 16:28:19 -07002930 if (b == 0 || b == ' ') break;
2931 if (b < '0' || b > ('0' + radix - 1)) {
2932 throw new IOException("Invalid number in header");
2933 }
2934 value = radix * value + (b - '0');
2935 }
2936 return value;
2937 }
2938
2939 String extractString(byte[] data, int offset, int maxChars) throws IOException {
2940 final int end = offset + maxChars;
2941 int eos = offset;
Christopher Tate3f6c77b2011-06-07 13:17:17 -07002942 // tar string fields terminate early with a NUL
2943 while (eos < end && data[eos] != 0) eos++;
Christopher Tate75a99702011-05-18 16:28:19 -07002944 return new String(data, offset, eos-offset, "US-ASCII");
2945 }
2946
2947 void sendStartRestore() {
2948 if (mObserver != null) {
2949 try {
2950 mObserver.onStartRestore();
2951 } catch (RemoteException e) {
2952 Slog.w(TAG, "full restore observer went away: startRestore");
2953 mObserver = null;
2954 }
2955 }
2956 }
2957
2958 void sendOnRestorePackage(String name) {
2959 if (mObserver != null) {
2960 try {
2961 // TODO: use a more user-friendly name string
2962 mObserver.onRestorePackage(name);
2963 } catch (RemoteException e) {
2964 Slog.w(TAG, "full restore observer went away: restorePackage");
2965 mObserver = null;
2966 }
2967 }
2968 }
2969
2970 void sendEndRestore() {
2971 if (mObserver != null) {
2972 try {
2973 mObserver.onEndRestore();
2974 } catch (RemoteException e) {
2975 Slog.w(TAG, "full restore observer went away: endRestore");
2976 mObserver = null;
2977 }
2978 }
2979 }
2980 }
2981
Christopher Tatedf01dea2009-06-09 20:45:02 -07002982 // ----- Restore handling -----
2983
Christopher Tate78dd4a72009-11-04 11:49:08 -08002984 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
2985 // If the target resides on the system partition, we allow it to restore
2986 // data from the like-named package in a restore set even if the signatures
2987 // do not match. (Unlike general applications, those flashed to the system
2988 // partition will be signed with the device's platform certificate, so on
2989 // different phones the same system app will have different signatures.)
2990 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002991 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08002992 return true;
2993 }
2994
Christopher Tate20efdf6b2009-06-18 19:41:36 -07002995 // Allow unsigned apps, but not signed on one device and unsigned on the other
2996 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08002997 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002998 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07002999 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07003000 if ((storedSigs == null || storedSigs.length == 0)
3001 && (deviceSigs == null || deviceSigs.length == 0)) {
3002 return true;
3003 }
3004 if (storedSigs == null || deviceSigs == null) {
3005 return false;
3006 }
3007
Christopher Tateabce4e82009-06-18 18:35:32 -07003008 // !!! TODO: this demands that every stored signature match one
3009 // that is present on device, and does not demand the converse.
3010 // Is this this right policy?
3011 int nStored = storedSigs.length;
3012 int nDevice = deviceSigs.length;
3013
3014 for (int i=0; i < nStored; i++) {
3015 boolean match = false;
3016 for (int j=0; j < nDevice; j++) {
3017 if (storedSigs[i].equals(deviceSigs[j])) {
3018 match = true;
3019 break;
3020 }
3021 }
3022 if (!match) {
3023 return false;
3024 }
3025 }
3026 return true;
3027 }
3028
Christopher Tate44a27902010-01-27 17:15:49 -08003029 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003030 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003031 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07003032 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08003033 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003034 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08003035 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003036 private boolean mNeedFullBackup;
Christopher Tate284f1bb2011-07-07 14:31:18 -07003037 private HashSet<String> mFilterSet;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003038
Christopher Tate5cbbf562009-06-22 16:44:51 -07003039 class RestoreRequest {
3040 public PackageInfo app;
3041 public int storedAppVersion;
3042
3043 RestoreRequest(PackageInfo _app, int _version) {
3044 app = _app;
3045 storedAppVersion = _version;
3046 }
3047 }
3048
Christopher Tate44a27902010-01-27 17:15:49 -08003049 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07003050 long restoreSetToken, PackageInfo targetPackage, int pmToken,
Christopher Tate284f1bb2011-07-07 14:31:18 -07003051 boolean needFullBackup, String[] filterSet) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003052 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003053 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003054 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08003055 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08003056 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07003057 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07003058
Christopher Tate284f1bb2011-07-07 14:31:18 -07003059 if (filterSet != null) {
3060 mFilterSet = new HashSet<String>();
3061 for (String pkg : filterSet) {
3062 mFilterSet.add(pkg);
3063 }
3064 } else {
3065 mFilterSet = null;
3066 }
3067
Christopher Tate5cb400b2009-06-25 16:03:14 -07003068 try {
3069 mStateDir = new File(mBaseStateDir, transport.transportDirName());
3070 } catch (RemoteException e) {
3071 // can't happen; the transport is local
3072 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003073 }
3074
Christopher Tatedf01dea2009-06-09 20:45:02 -07003075 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003076 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003077 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08003078 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate284f1bb2011-07-07 14:31:18 -07003079 + " mTargetPackage=" + mTargetPackage + " mFilterSet=" + mFilterSet
3080 + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003081
Christopher Tateb49ceb32010-02-08 16:22:24 -08003082 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07003083 int error = -1; // assume error
3084
Dan Egnorefe52642009-06-24 00:16:33 -07003085 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07003086 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07003087 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003088 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07003089
Dan Egnorefe52642009-06-24 00:16:33 -07003090 // Get the list of all packages which have backup enabled.
3091 // (Include the Package Manager metadata pseudo-package first.)
3092 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
3093 PackageInfo omPackage = new PackageInfo();
3094 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
3095 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07003096
Dan Egnorefe52642009-06-24 00:16:33 -07003097 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003098 if (mTargetPackage == null) {
Christopher Tate284f1bb2011-07-07 14:31:18 -07003099 // if there's a filter set, strip out anything that isn't
3100 // present before proceeding
3101 if (mFilterSet != null) {
3102 for (int i = agentPackages.size() - 1; i >= 0; i--) {
3103 final PackageInfo pkg = agentPackages.get(i);
3104 if (! mFilterSet.contains(pkg.packageName)) {
3105 agentPackages.remove(i);
3106 }
3107 }
3108 if (DEBUG) {
3109 Slog.i(TAG, "Post-filter package set for restore:");
3110 for (PackageInfo p : agentPackages) {
3111 Slog.i(TAG, " " + p);
3112 }
3113 }
3114 }
Christopher Tate84725812010-02-04 15:52:40 -08003115 restorePackages.addAll(agentPackages);
3116 } else {
3117 // Just one package to attempt restore of
3118 restorePackages.add(mTargetPackage);
3119 }
Dan Egnorefe52642009-06-24 00:16:33 -07003120
Christopher Tate7d562ec2009-06-25 18:03:43 -07003121 // let the observer know that we're running
3122 if (mObserver != null) {
3123 try {
3124 // !!! TODO: get an actual count from the transport after
3125 // its startRestore() runs?
3126 mObserver.restoreStarting(restorePackages.size());
3127 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003128 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003129 mObserver = null;
3130 }
3131 }
3132
Dan Egnor01445162009-09-21 17:04:05 -07003133 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
3134 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003135 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003136 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003137 return;
3138 }
3139
3140 String packageName = mTransport.nextRestorePackage();
3141 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003142 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003143 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003144 return;
3145 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003146 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003147 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003148 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07003149 return;
3150 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003151 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07003152 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003153 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003154 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003155 return;
3156 }
3157
3158 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08003159 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07003160 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07003161 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
3162 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07003163
Christopher Tate8c032472009-07-02 14:28:47 -07003164 // Verify that the backup set includes metadata. If not, we can't do
3165 // signature/version verification etc, so we simply do not proceed with
3166 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07003167 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003168 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003169 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003170 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07003171 return;
3172 }
3173
Christopher Tate7d562ec2009-06-25 18:03:43 -07003174 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07003175 for (;;) {
3176 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003177
Dan Egnorefe52642009-06-24 00:16:33 -07003178 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003179 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003180 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07003181 return;
3182 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003183 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07003184 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003185 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003186
Christopher Tate7d562ec2009-06-25 18:03:43 -07003187 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07003188 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07003189 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07003190 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003191 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003192 mObserver = null;
3193 }
3194 }
3195
Dan Egnorefe52642009-06-24 00:16:33 -07003196 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
3197 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003198 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003199 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003200 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003201 continue;
3202 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003203
Dan Egnorbb9001c2009-07-27 12:20:13 -07003204 PackageInfo packageInfo;
3205 try {
3206 int flags = PackageManager.GET_SIGNATURES;
3207 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
3208 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003209 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003210 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003211 "Package missing on device");
3212 continue;
3213 }
3214
Dan Egnorefe52642009-06-24 00:16:33 -07003215 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08003216 // Data is from a "newer" version of the app than we have currently
3217 // installed. If the app has not declared that it is prepared to
3218 // handle this case, we do not attempt the restore.
3219 if ((packageInfo.applicationInfo.flags
3220 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
3221 String message = "Version " + metaInfo.versionCode
3222 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003223 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08003224 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
3225 packageName, message);
3226 continue;
3227 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003228 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08003229 + " > installed " + packageInfo.versionCode
3230 + " but restoreAnyVersion");
3231 }
Dan Egnorefe52642009-06-24 00:16:33 -07003232 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003233
Christopher Tate78dd4a72009-11-04 11:49:08 -08003234 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003235 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003236 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003237 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07003238 continue;
3239 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003240
Joe Onorato8a9b2202010-02-26 18:56:32 -08003241 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07003242 + " restore version [" + metaInfo.versionCode
3243 + "] is compatible with installed version ["
3244 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07003245
Christopher Tate3de55bc2010-03-12 17:28:08 -08003246 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07003247 IBackupAgent agent = bindToAgentSynchronous(
3248 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08003249 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07003250 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003251 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003252 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07003253 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07003254 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07003255 }
3256
Christopher Tate5e1ab332009-09-01 20:32:49 -07003257 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07003258 try {
Chris Tate249345b2010-10-29 12:57:04 -07003259 processOneRestore(packageInfo, metaInfo.versionCode, agent,
3260 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003261 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07003262 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003263 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07003264 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07003265
3266 // The agent was probably running with a stub Application object,
3267 // which isn't a valid run mode for the main app logic. Shut
3268 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08003269 // usual full initialization. Note that this is only done for
3270 // full-system restores: when a single app has requested a restore,
3271 // it is explicitly not killed following that operation.
3272 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07003273 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003274 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003275 + packageInfo.applicationInfo.processName);
3276 mActivityManager.killApplicationProcess(
3277 packageInfo.applicationInfo.processName,
3278 packageInfo.applicationInfo.uid);
3279 }
Dan Egnorefe52642009-06-24 00:16:33 -07003280 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003281 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003282
3283 // if we get this far, report success to the observer
3284 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07003285 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003286 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003287 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003288 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003289 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003290 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003291
Dan Egnorefe52642009-06-24 00:16:33 -07003292 try {
3293 mTransport.finishRestore();
3294 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003295 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07003296 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07003297
3298 if (mObserver != null) {
3299 try {
3300 mObserver.restoreFinished(error);
3301 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003302 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07003303 }
3304 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003305
Christopher Tate84725812010-02-04 15:52:40 -08003306 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08003307 // ancestral dataset, as well as the set of apps that are possibly
3308 // restoreable from the dataset
3309 if (mTargetPackage == null && pmAgent != null) {
3310 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08003311 mAncestralToken = mToken;
3312 writeRestoreTokens();
3313 }
3314
Christopher Tate1bb69062010-02-19 17:02:12 -08003315 // We must under all circumstances tell the Package Manager to
3316 // proceed with install notifications if it's waiting for us.
3317 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003318 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08003319 try {
3320 mPackageManagerBinder.finishPackageInstall(mPmToken);
3321 } catch (RemoteException e) { /* can't happen */ }
3322 }
3323
Christopher Tate73a3cb32010-12-13 18:27:26 -08003324 // Furthermore we need to reset the session timeout clock
3325 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3326 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
3327 TIMEOUT_RESTORE_INTERVAL);
3328
Christopher Tateb6787f22009-07-02 17:40:45 -07003329 // done; we can finally release the wakelock
3330 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07003331 }
3332 }
3333
Dan Egnorefe52642009-06-24 00:16:33 -07003334 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07003335 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
3336 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07003337 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07003338 final String packageName = app.packageName;
3339
Joe Onorato8a9b2202010-02-26 18:56:32 -08003340 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003341
Christopher Tatec7b31e32009-06-10 15:49:30 -07003342 // !!! TODO: get the dirs from the transport
3343 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07003344 File newStateName = new File(mStateDir, packageName + ".new");
3345 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003346
Dan Egnorbb9001c2009-07-27 12:20:13 -07003347 ParcelFileDescriptor backupData = null;
3348 ParcelFileDescriptor newState = null;
3349
Christopher Tate4a627c72011-04-01 14:43:32 -07003350 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003351 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07003352 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07003353 backupData = ParcelFileDescriptor.open(backupDataName,
3354 ParcelFileDescriptor.MODE_READ_WRITE |
3355 ParcelFileDescriptor.MODE_CREATE |
3356 ParcelFileDescriptor.MODE_TRUNCATE);
3357
Dan Egnor01445162009-09-21 17:04:05 -07003358 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003359 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003360 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07003361 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07003362 }
3363
3364 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07003365 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07003366 backupData = ParcelFileDescriptor.open(backupDataName,
3367 ParcelFileDescriptor.MODE_READ_ONLY);
3368
Dan Egnorbb9001c2009-07-27 12:20:13 -07003369 newState = ParcelFileDescriptor.open(newStateName,
3370 ParcelFileDescriptor.MODE_READ_WRITE |
3371 ParcelFileDescriptor.MODE_CREATE |
3372 ParcelFileDescriptor.MODE_TRUNCATE);
3373
Christopher Tate44a27902010-01-27 17:15:49 -08003374 // Kick off the restore, checking for hung agents
3375 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
3376 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
3377 boolean success = waitUntilOperationComplete(token);
3378
3379 if (!success) {
3380 throw new RuntimeException("restore timeout");
3381 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07003382
3383 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07003384 //
3385 // !!! TODO: the restored data should be migrated on the server
3386 // side into the current dataset. In that case the new state file
3387 // we just created would reflect the data already extant in the
3388 // backend, so there'd be nothing more to do. Until that happens,
3389 // however, we need to make sure that we record the data to the
3390 // current backend dataset. (Yes, this means shipping the data over
3391 // the wire in both directions. That's bad, but consistency comes
3392 // first, then efficiency.) Once we introduce server-side data
3393 // migration to the newly-restored device's dataset, we will change
3394 // the following from a discard of the newly-written state to the
3395 // "correct" operation of renaming into the canonical state blob.
3396 newStateName.delete(); // TODO: remove; see above comment
3397 //newStateName.renameTo(savedStateName); // TODO: replace with this
3398
Dan Egnorbb9001c2009-07-27 12:20:13 -07003399 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003400 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07003401 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003402 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003403 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07003404
Christopher Tate96733042009-07-20 14:49:13 -07003405 // If the agent fails restore, it might have put the app's data
3406 // into an incoherent state. For consistency we wipe its data
3407 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07003408 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07003409 } finally {
3410 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07003411 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
3412 try { if (newState != null) newState.close(); } catch (IOException e) {}
3413 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07003414 synchronized (mCurrentOperations) {
3415 mCurrentOperations.delete(token);
3416 }
Chris Tate249345b2010-10-29 12:57:04 -07003417
3418 // If we know a priori that we'll need to perform a full post-restore backup
3419 // pass, clear the new state file data. This means we're discarding work that
3420 // was just done by the app's agent, but this way the agent doesn't need to
3421 // take any special action based on global device state.
3422 if (needFullBackup) {
3423 newStateName.delete();
3424 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07003425 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003426 }
3427 }
3428
Christopher Tate44a27902010-01-27 17:15:49 -08003429 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07003430 IBackupTransport mTransport;
3431 PackageInfo mPackage;
3432
Christopher Tate44a27902010-01-27 17:15:49 -08003433 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07003434 mTransport = transport;
3435 mPackage = packageInfo;
3436 }
3437
Christopher Tateee0e78a2009-07-02 11:17:03 -07003438 public void run() {
3439 try {
3440 // Clear the on-device backup state to ensure a full backup next time
3441 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
3442 File stateFile = new File(stateDir, mPackage.packageName);
3443 stateFile.delete();
3444
3445 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07003446 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07003447 mTransport.clearBackupData(mPackage);
3448 } catch (RemoteException e) {
3449 // can't happen; the transport is local
3450 } finally {
3451 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07003452 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07003453 mTransport.finishBackup();
3454 } catch (RemoteException e) {
3455 // can't happen; the transport is local
3456 }
Christopher Tateb6787f22009-07-02 17:40:45 -07003457
3458 // Last but not least, release the cpu
3459 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07003460 }
3461 }
3462 }
3463
Christopher Tate44a27902010-01-27 17:15:49 -08003464 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003465 HashSet<String> mQueue;
3466
Christopher Tate44a27902010-01-27 17:15:49 -08003467 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003468 mQueue = transportNames;
3469 }
3470
Christopher Tate4cc86e12009-09-21 19:36:51 -07003471 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07003472 try {
3473 for (String transportName : mQueue) {
3474 IBackupTransport transport = getTransport(transportName);
3475 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003476 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07003477 continue;
3478 }
3479
Joe Onorato8a9b2202010-02-26 18:56:32 -08003480 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003481 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07003482 long startRealtime = SystemClock.elapsedRealtime();
3483 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07003484
Christopher Tate4cc86e12009-09-21 19:36:51 -07003485 if (status == BackupConstants.TRANSPORT_OK) {
3486 status = transport.finishBackup();
3487 }
3488
3489 // Okay, the wipe really happened. Clean up our local bookkeeping.
3490 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003491 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07003492 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003493 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07003494 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003495 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003496 synchronized (mQueueLock) {
3497 recordInitPendingLocked(false, transportName);
3498 }
Dan Egnor726247c2009-09-29 19:12:31 -07003499 } else {
3500 // If this didn't work, requeue this one and try again
3501 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08003502 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003503 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07003504 synchronized (mQueueLock) {
3505 recordInitPendingLocked(true, transportName);
3506 }
3507 // do this via another alarm to make sure of the wakelock states
3508 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08003509 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07003510 + transportName + " resched in " + delay);
3511 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
3512 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003513 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07003514 }
3515 } catch (RemoteException e) {
3516 // can't happen; the transports are local
3517 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003518 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003519 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08003520 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07003521 mWakelock.release();
3522 }
3523 }
3524 }
3525
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003526 private void dataChangedImpl(String packageName) {
3527 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
3528 dataChangedImpl(packageName, targets);
3529 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07003530
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003531 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07003532 // Record that we need a backup pass for the caller. Since multiple callers
3533 // may share a uid, we need to note all candidates within that uid and schedule
3534 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003535 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003536
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003537 if (targets == null) {
3538 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
3539 + " uid=" + Binder.getCallingUid());
3540 return;
3541 }
3542
3543 synchronized (mQueueLock) {
3544 // Note that this client has made data changes that need to be backed up
3545 for (ApplicationInfo app : targets) {
3546 // validate the caller-supplied package name against the known set of
3547 // packages associated with this uid
3548 if (app.packageName.equals(packageName)) {
3549 // Add the caller to the set of pending backups. If there is
3550 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07003551 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08003552 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003553 // Journal this request in case of crash. The put()
3554 // operation returned null when this package was not already
3555 // in the set; we want to avoid touching the disk redundantly.
3556 writeToJournalLocked(packageName);
3557
3558 if (DEBUG) {
3559 int numKeys = mPendingBackups.size();
3560 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
3561 for (BackupRequest b : mPendingBackups.values()) {
3562 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
3563 }
3564 }
3565 }
3566 }
3567 }
3568 }
3569 }
3570
3571 // Note: packageName is currently unused, but may be in the future
3572 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07003573 // If the caller does not hold the BACKUP permission, it can only request a
3574 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07003575 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07003576 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003577 synchronized (mBackupParticipants) {
3578 return mBackupParticipants.get(Binder.getCallingUid());
3579 }
3580 }
3581
3582 // a caller with full permission can ask to back up any participating app
3583 // !!! TODO: allow backup of ANY app?
3584 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
3585 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07003586 int N = mBackupParticipants.size();
3587 for (int i = 0; i < N; i++) {
3588 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
3589 if (s != null) {
3590 targets.addAll(s);
3591 }
3592 }
3593 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003594 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07003595 }
Christopher Tate46758122009-05-06 11:22:00 -07003596
Christopher Tatecde87f42009-06-12 12:55:53 -07003597 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07003598 RandomAccessFile out = null;
3599 try {
3600 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
3601 out = new RandomAccessFile(mJournal, "rws");
3602 out.seek(out.length());
3603 out.writeUTF(str);
3604 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003605 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07003606 mJournal = null;
3607 } finally {
3608 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07003609 }
3610 }
3611
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07003612 // ----- IBackupManager binder interface -----
3613
3614 public void dataChanged(final String packageName) {
3615 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
3616 if (targets == null) {
3617 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
3618 + " uid=" + Binder.getCallingUid());
3619 return;
3620 }
3621
3622 mBackupHandler.post(new Runnable() {
3623 public void run() {
3624 dataChangedImpl(packageName, targets);
3625 }
3626 });
3627 }
3628
Christopher Tateee0e78a2009-07-02 11:17:03 -07003629 // Clear the given package's backup data from the current transport
3630 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003631 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07003632 PackageInfo info;
3633 try {
3634 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
3635 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003636 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003637 return;
3638 }
3639
3640 // If the caller does not hold the BACKUP permission, it can only request a
3641 // wipe of its own backed-up data.
3642 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07003643 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07003644 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
3645 apps = mBackupParticipants.get(Binder.getCallingUid());
3646 } else {
3647 // a caller with full permission can ask to back up any participating app
3648 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08003649 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003650 apps = new HashSet<ApplicationInfo>();
3651 int N = mBackupParticipants.size();
3652 for (int i = 0; i < N; i++) {
3653 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
3654 if (s != null) {
3655 apps.addAll(s);
3656 }
3657 }
3658 }
3659
3660 // now find the given package in the set of candidate apps
3661 for (ApplicationInfo app : apps) {
3662 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003663 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07003664 // found it; fire off the clear request
3665 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07003666 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07003667 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07003668 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
3669 new ClearParams(getTransport(mCurrentTransport), info));
3670 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07003671 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07003672 }
3673 break;
3674 }
3675 }
3676 }
3677
Christopher Tateace7f092009-06-15 18:07:25 -07003678 // Run a backup pass immediately for any applications that have declared
3679 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07003680 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04003681 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07003682
Joe Onorato8a9b2202010-02-26 18:56:32 -08003683 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07003684 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07003685 // Because the alarms we are using can jitter, and we want an *immediate*
3686 // backup pass to happen, we restart the timer beginning with "next time,"
3687 // then manually fire the backup trigger intent ourselves.
3688 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07003689 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07003690 mRunBackupIntent.send();
3691 } catch (PendingIntent.CanceledException e) {
3692 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08003693 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07003694 }
Christopher Tate46758122009-05-06 11:22:00 -07003695 }
3696 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003697
Christopher Tate4a627c72011-04-01 14:43:32 -07003698 // Run a *full* backup pass for the given package, writing the resulting data stream
3699 // to the supplied file descriptor. This method is synchronous and does not return
3700 // to the caller until the backup has been completed.
3701 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
3702 boolean doAllApps, String[] pkgList) {
3703 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
3704
3705 // Validate
3706 if (!doAllApps) {
3707 if (!includeShared) {
3708 // If we're backing up shared data (sdcard or equivalent), then we can run
3709 // without any supplied app names. Otherwise, we'd be doing no work, so
3710 // report the error.
3711 if (pkgList == null || pkgList.length == 0) {
3712 throw new IllegalArgumentException(
3713 "Backup requested but neither shared nor any apps named");
3714 }
3715 }
3716 }
3717
3718 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
3719 + " shared=" + includeShared + " all=" + doAllApps
3720 + " pkgs=" + pkgList);
3721
3722 long oldId = Binder.clearCallingIdentity();
3723 try {
3724 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
3725 doAllApps, pkgList);
3726 final int token = generateToken();
3727 synchronized (mFullConfirmations) {
3728 mFullConfirmations.put(token, params);
3729 }
3730
Christopher Tate75a99702011-05-18 16:28:19 -07003731 // start up the confirmation UI
3732 if (DEBUG) Slog.d(TAG, "Starting backup confirmation UI, token=" + token);
3733 if (!startConfirmationUi(token, FullBackup.FULL_BACKUP_INTENT_ACTION)) {
3734 Slog.e(TAG, "Unable to launch full backup confirmation");
Christopher Tate4a627c72011-04-01 14:43:32 -07003735 mFullConfirmations.delete(token);
3736 return;
3737 }
Christopher Tate75a99702011-05-18 16:28:19 -07003738
3739 // make sure the screen is lit for the user interaction
Christopher Tate4a627c72011-04-01 14:43:32 -07003740 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3741
3742 // start the confirmation countdown
Christopher Tate75a99702011-05-18 16:28:19 -07003743 startConfirmationTimeout(token, params);
Christopher Tate4a627c72011-04-01 14:43:32 -07003744
3745 // wait for the backup to be performed
3746 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
3747 waitForCompletion(params);
Christopher Tate4a627c72011-04-01 14:43:32 -07003748 } finally {
Christopher Tate4a627c72011-04-01 14:43:32 -07003749 try {
3750 fd.close();
3751 } catch (IOException e) {
3752 // just eat it
3753 }
Christopher Tate75a99702011-05-18 16:28:19 -07003754 Binder.restoreCallingIdentity(oldId);
Christopher Tate4a627c72011-04-01 14:43:32 -07003755 }
Christopher Tate75a99702011-05-18 16:28:19 -07003756 if (DEBUG) Slog.d(TAG, "Full backup done; returning to caller");
3757 }
3758
3759 public void fullRestore(ParcelFileDescriptor fd) {
3760 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
3761 Slog.i(TAG, "Beginning full restore...");
3762
3763 long oldId = Binder.clearCallingIdentity();
3764
3765 try {
3766 FullRestoreParams params = new FullRestoreParams(fd);
3767 final int token = generateToken();
3768 synchronized (mFullConfirmations) {
3769 mFullConfirmations.put(token, params);
3770 }
3771
3772 // start up the confirmation UI
3773 if (DEBUG) Slog.d(TAG, "Starting restore confirmation UI, token=" + token);
3774 if (!startConfirmationUi(token, FullBackup.FULL_RESTORE_INTENT_ACTION)) {
3775 Slog.e(TAG, "Unable to launch full restore confirmation");
3776 mFullConfirmations.delete(token);
3777 return;
3778 }
3779
3780 // make sure the screen is lit for the user interaction
3781 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3782
3783 // start the confirmation countdown
3784 startConfirmationTimeout(token, params);
3785
3786 // wait for the restore to be performed
3787 if (DEBUG) Slog.d(TAG, "Waiting for full restore completion...");
3788 waitForCompletion(params);
3789 } finally {
3790 try {
3791 fd.close();
3792 } catch (IOException e) {
3793 Slog.w(TAG, "Error trying to close fd after full restore: " + e);
3794 }
3795 Binder.restoreCallingIdentity(oldId);
3796 Slog.i(TAG, "Full restore completed");
3797 }
3798 }
3799
3800 boolean startConfirmationUi(int token, String action) {
3801 try {
3802 Intent confIntent = new Intent(action);
3803 confIntent.setClassName("com.android.backupconfirm",
3804 "com.android.backupconfirm.BackupRestoreConfirmation");
3805 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
3806 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3807 mContext.startActivity(confIntent);
3808 } catch (ActivityNotFoundException e) {
3809 return false;
3810 }
3811 return true;
3812 }
3813
3814 void startConfirmationTimeout(int token, FullParams params) {
3815 if (DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
3816 + TIMEOUT_FULL_CONFIRMATION + " millis");
3817 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
3818 token, 0, params);
3819 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
Christopher Tate4a627c72011-04-01 14:43:32 -07003820 }
3821
3822 void waitForCompletion(FullParams params) {
3823 synchronized (params.latch) {
3824 while (params.latch.get() == false) {
3825 try {
3826 params.latch.wait();
3827 } catch (InterruptedException e) { /* never interrupted */ }
3828 }
3829 }
3830 }
3831
3832 void signalFullBackupRestoreCompletion(FullParams params) {
3833 synchronized (params.latch) {
3834 params.latch.set(true);
3835 params.latch.notifyAll();
3836 }
3837 }
3838
3839 // Confirm that the previously-requested full backup/restore operation can proceed. This
3840 // is used to require a user-facing disclosure about the operation.
3841 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
3842 IFullBackupRestoreObserver observer) {
3843 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
3844 + " allow=" + allow);
3845
3846 // TODO: possibly require not just this signature-only permission, but even
3847 // require that the specific designated confirmation-UI app uid is the caller?
3848 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
3849
3850 long oldId = Binder.clearCallingIdentity();
3851 try {
3852
3853 FullParams params;
3854 synchronized (mFullConfirmations) {
3855 params = mFullConfirmations.get(token);
3856 if (params != null) {
3857 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
3858 mFullConfirmations.delete(token);
3859
3860 if (allow) {
3861 params.observer = observer;
3862 final int verb = params instanceof FullBackupParams
Christopher Tate75a99702011-05-18 16:28:19 -07003863 ? MSG_RUN_FULL_BACKUP
Christopher Tate4a627c72011-04-01 14:43:32 -07003864 : MSG_RUN_FULL_RESTORE;
3865
Christopher Tate75a99702011-05-18 16:28:19 -07003866 if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
Christopher Tate4a627c72011-04-01 14:43:32 -07003867 mWakelock.acquire();
3868 Message msg = mBackupHandler.obtainMessage(verb, params);
3869 mBackupHandler.sendMessage(msg);
3870 } else {
3871 Slog.w(TAG, "User rejected full backup/restore operation");
3872 // indicate completion without having actually transferred any data
3873 signalFullBackupRestoreCompletion(params);
3874 }
3875 } else {
3876 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
3877 }
3878 }
3879 } finally {
3880 Binder.restoreCallingIdentity(oldId);
3881 }
3882 }
3883
Christopher Tate8031a3d2009-07-06 16:36:05 -07003884 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07003885 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07003886 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4a627c72011-04-01 14:43:32 -07003887 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07003888
Joe Onorato8a9b2202010-02-26 18:56:32 -08003889 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003890
Christopher Tate6ef58a12009-06-29 14:56:28 -07003891 boolean wasEnabled = mEnabled;
3892 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07003893 Settings.Secure.putInt(mContext.getContentResolver(),
3894 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07003895 mEnabled = enable;
3896 }
3897
Christopher Tate49401dd2009-07-01 12:34:29 -07003898 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07003899 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07003900 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07003901 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07003902 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07003903 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08003904 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07003905
Christopher Tateb6787f22009-07-02 17:40:45 -07003906 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07003907
3908 // This also constitutes an opt-out, so we wipe any data for
3909 // this device from the backend. We start that process with
3910 // an alarm in order to guarantee wakelock states.
3911 if (wasEnabled && mProvisioned) {
3912 // NOTE: we currently flush every registered transport, not just
3913 // the currently-active one.
3914 HashSet<String> allTransports;
3915 synchronized (mTransports) {
3916 allTransports = new HashSet<String>(mTransports.keySet());
3917 }
3918 // build the set of transports for which we are posting an init
3919 for (String transport : allTransports) {
3920 recordInitPendingLocked(true, transport);
3921 }
3922 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
3923 mRunInitIntent);
3924 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07003925 }
3926 }
Christopher Tate49401dd2009-07-01 12:34:29 -07003927 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07003928
Christopher Tatecce9da52010-02-03 15:11:15 -08003929 // Enable/disable automatic restore of app data at install time
3930 public void setAutoRestore(boolean doAutoRestore) {
3931 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3932 "setBackupEnabled");
3933
Joe Onorato8a9b2202010-02-26 18:56:32 -08003934 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08003935
3936 synchronized (this) {
3937 Settings.Secure.putInt(mContext.getContentResolver(),
3938 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
3939 mAutoRestore = doAutoRestore;
3940 }
3941 }
3942
Christopher Tate8031a3d2009-07-06 16:36:05 -07003943 // Mark the backup service as having been provisioned
3944 public void setBackupProvisioned(boolean available) {
3945 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3946 "setBackupProvisioned");
3947
3948 boolean wasProvisioned = mProvisioned;
3949 synchronized (this) {
3950 Settings.Secure.putInt(mContext.getContentResolver(),
3951 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
3952 mProvisioned = available;
3953 }
3954
3955 synchronized (mQueueLock) {
3956 if (available && !wasProvisioned && mEnabled) {
3957 // we're now good to go, so start the backup alarms
3958 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
3959 } else if (!available) {
3960 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08003961 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07003962 mAlarmManager.cancel(mRunBackupIntent);
3963 }
3964 }
3965 }
3966
3967 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07003968 // We used to use setInexactRepeating(), but that may be linked to
3969 // backups running at :00 more often than not, creating load spikes.
3970 // Schedule at an exact time for now, and also add a bit of "fuzz".
3971
3972 Random random = new Random();
3973 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
3974 random.nextInt(FUZZ_MILLIS);
3975 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
3976 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07003977 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07003978 }
3979
Christopher Tate6ef58a12009-06-29 14:56:28 -07003980 // Report whether the backup mechanism is currently enabled
3981 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04003982 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07003983 return mEnabled; // no need to synchronize just to read it
3984 }
3985
Christopher Tate91717492009-06-26 21:07:13 -07003986 // Report the name of the currently active transport
3987 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04003988 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07003989 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08003990 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07003991 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07003992 }
3993
Christopher Tate91717492009-06-26 21:07:13 -07003994 // Report all known, available backup transports
3995 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07003996 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07003997
Christopher Tate91717492009-06-26 21:07:13 -07003998 String[] list = null;
3999 ArrayList<String> known = new ArrayList<String>();
4000 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
4001 if (entry.getValue() != null) {
4002 known.add(entry.getKey());
4003 }
4004 }
4005
4006 if (known.size() > 0) {
4007 list = new String[known.size()];
4008 known.toArray(list);
4009 }
4010 return list;
4011 }
4012
4013 // Select which transport to use for the next backup operation. If the given
4014 // name is not one of the available transports, no action is taken and the method
4015 // returns null.
4016 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04004017 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07004018
4019 synchronized (mTransports) {
4020 String prevTransport = null;
4021 if (mTransports.get(transport) != null) {
4022 prevTransport = mCurrentTransport;
4023 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07004024 Settings.Secure.putString(mContext.getContentResolver(),
4025 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004026 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07004027 + " returning " + prevTransport);
4028 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004029 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07004030 }
4031 return prevTransport;
4032 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004033 }
4034
Christopher Tatef5e1c292010-12-08 18:40:26 -08004035 // Supply the configuration Intent for the given transport. If the name is not one
4036 // of the available transports, or if the transport does not supply any configuration
4037 // UI, the method returns null.
4038 public Intent getConfigurationIntent(String transportName) {
4039 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4040 "getConfigurationIntent");
4041
4042 synchronized (mTransports) {
4043 final IBackupTransport transport = mTransports.get(transportName);
4044 if (transport != null) {
4045 try {
4046 final Intent intent = transport.configurationIntent();
4047 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
4048 + intent);
4049 return intent;
4050 } catch (RemoteException e) {
4051 /* fall through to return null */
4052 }
4053 }
4054 }
4055
4056 return null;
4057 }
4058
4059 // Supply the configuration summary string for the given transport. If the name is
4060 // not one of the available transports, or if the transport does not supply any
4061 // summary / destination string, the method can return null.
4062 //
4063 // This string is used VERBATIM as the summary text of the relevant Settings item!
4064 public String getDestinationString(String transportName) {
4065 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4066 "getConfigurationIntent");
4067
4068 synchronized (mTransports) {
4069 final IBackupTransport transport = mTransports.get(transportName);
4070 if (transport != null) {
4071 try {
4072 final String text = transport.currentDestinationString();
4073 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
4074 return text;
4075 } catch (RemoteException e) {
4076 /* fall through to return null */
4077 }
4078 }
4079 }
4080
4081 return null;
4082 }
4083
Christopher Tate043dadc2009-06-02 16:11:00 -07004084 // Callback: a requested backup agent has been instantiated. This should only
4085 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004086 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07004087 synchronized(mAgentConnectLock) {
4088 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004089 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07004090 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
4091 mConnectedAgent = agent;
4092 mConnecting = false;
4093 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004094 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004095 + " claiming agent connected");
4096 }
4097 mAgentConnectLock.notifyAll();
4098 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004099 }
4100
4101 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
4102 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07004103 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07004104 public void agentDisconnected(String packageName) {
4105 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07004106 synchronized(mAgentConnectLock) {
4107 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
4108 mConnectedAgent = null;
4109 mConnecting = false;
4110 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004111 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07004112 + " claiming agent disconnected");
4113 }
4114 mAgentConnectLock.notifyAll();
4115 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004116 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004117
Christopher Tate1bb69062010-02-19 17:02:12 -08004118 // An application being installed will need a restore pass, then the Package Manager
4119 // will need to be told when the restore is finished.
4120 public void restoreAtInstall(String packageName, int token) {
4121 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004122 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08004123 + " attemping install-time restore");
4124 return;
4125 }
4126
4127 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004128 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08004129 + " token=" + Integer.toHexString(token));
4130
Christopher Tatef0872722010-02-25 15:22:48 -08004131 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08004132 // okay, we're going to attempt a restore of this package from this restore set.
4133 // The eventual message back into the Package Manager to run the post-install
4134 // steps for 'token' will be issued from the restore handling code.
4135
4136 // We can use a synthetic PackageInfo here because:
4137 // 1. We know it's valid, since the Package Manager supplied the name
4138 // 2. Only the packageName field will be used by the restore code
4139 PackageInfo pkg = new PackageInfo();
4140 pkg.packageName = packageName;
4141
4142 mWakelock.acquire();
4143 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4144 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07004145 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08004146 mBackupHandler.sendMessage(msg);
4147 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08004148 // Auto-restore disabled or no way to attempt a restore; just tell the Package
4149 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004150 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08004151 try {
4152 mPackageManagerBinder.finishPackageInstall(token);
4153 } catch (RemoteException e) { /* can't happen */ }
4154 }
4155 }
4156
Christopher Tate8c850b72009-06-07 19:33:20 -07004157 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08004158 public IRestoreSession beginRestoreSession(String packageName, String transport) {
4159 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
4160 + " transport=" + transport);
4161
4162 boolean needPermission = true;
4163 if (transport == null) {
4164 transport = mCurrentTransport;
4165
4166 if (packageName != null) {
4167 PackageInfo app = null;
4168 try {
4169 app = mPackageManager.getPackageInfo(packageName, 0);
4170 } catch (NameNotFoundException nnf) {
4171 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
4172 throw new IllegalArgumentException("Package " + packageName + " not found");
4173 }
4174
4175 if (app.applicationInfo.uid == Binder.getCallingUid()) {
4176 // So: using the current active transport, and the caller has asked
4177 // that its own package will be restored. In this narrow use case
4178 // we do not require the caller to hold the permission.
4179 needPermission = false;
4180 }
4181 }
4182 }
4183
4184 if (needPermission) {
4185 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4186 "beginRestoreSession");
4187 } else {
4188 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
4189 }
Christopher Tatef68eb502009-06-16 11:02:01 -07004190
4191 synchronized(this) {
4192 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004193 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07004194 return null;
4195 }
Chris Tate44ab8452010-11-16 15:10:49 -08004196 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08004197 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07004198 }
4199 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07004200 }
Christopher Tate043dadc2009-06-02 16:11:00 -07004201
Christopher Tate73a3cb32010-12-13 18:27:26 -08004202 void clearRestoreSession(ActiveRestoreSession currentSession) {
4203 synchronized(this) {
4204 if (currentSession != mActiveRestoreSession) {
4205 Slog.e(TAG, "ending non-current restore session");
4206 } else {
4207 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
4208 mActiveRestoreSession = null;
4209 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
4210 }
4211 }
4212 }
4213
Christopher Tate44a27902010-01-27 17:15:49 -08004214 // Note that a currently-active backup agent has notified us that it has
4215 // completed the given outstanding asynchronous backup/restore operation.
4216 public void opComplete(int token) {
4217 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004218 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08004219 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
4220 mCurrentOpLock.notifyAll();
4221 }
4222 }
4223
Christopher Tate9b3905c2009-06-08 15:24:01 -07004224 // ----- Restore session -----
4225
Christopher Tate80202c82010-01-25 19:37:47 -08004226 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07004227 private static final String TAG = "RestoreSession";
4228
Chris Tate44ab8452010-11-16 15:10:49 -08004229 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004230 private IBackupTransport mRestoreTransport = null;
4231 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08004232 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07004233
Chris Tate44ab8452010-11-16 15:10:49 -08004234 ActiveRestoreSession(String packageName, String transport) {
4235 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07004236 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07004237 }
4238
4239 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07004240 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04004241 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004242 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004243 if (observer == null) {
4244 throw new IllegalArgumentException("Observer must not be null");
4245 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004246
Christopher Tate73a3cb32010-12-13 18:27:26 -08004247 if (mEnded) {
4248 throw new IllegalStateException("Restore session already ended");
4249 }
4250
Christopher Tate1bb69062010-02-19 17:02:12 -08004251 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07004252 try {
Christopher Tate43383042009-07-13 15:17:13 -07004253 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004254 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07004255 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07004256 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07004257 // spin off the transport request to our service thread
4258 mWakelock.acquire();
4259 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
4260 new RestoreGetSetsParams(mRestoreTransport, this, observer));
4261 mBackupHandler.sendMessage(msg);
4262 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07004263 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004264 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07004265 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08004266 } finally {
4267 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07004268 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07004269 }
4270
Christopher Tate84725812010-02-04 15:52:40 -08004271 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07004272 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4273 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004274
Chris Tate44ab8452010-11-16 15:10:49 -08004275 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07004276 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004277
Christopher Tate73a3cb32010-12-13 18:27:26 -08004278 if (mEnded) {
4279 throw new IllegalStateException("Restore session already ended");
4280 }
4281
Dan Egnor0084da52009-07-29 12:57:16 -07004282 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08004283 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4284 return -1;
4285 }
4286
4287 if (mPackageName != null) {
4288 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07004289 return -1;
4290 }
4291
Christopher Tate21ab6a52009-09-24 18:01:46 -07004292 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07004293 for (int i = 0; i < mRestoreSets.length; i++) {
4294 if (token == mRestoreSets[i].token) {
4295 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07004296 mWakelock.acquire();
4297 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004298 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07004299 mBackupHandler.sendMessage(msg);
4300 Binder.restoreCallingIdentity(oldId);
4301 return 0;
4302 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07004303 }
4304 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07004305
Joe Onorato8a9b2202010-02-26 18:56:32 -08004306 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07004307 return -1;
4308 }
4309
Christopher Tate284f1bb2011-07-07 14:31:18 -07004310 public synchronized int restoreSome(long token, IRestoreObserver observer,
4311 String[] packages) {
4312 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
4313 "performRestore");
4314
4315 if (DEBUG) {
4316 StringBuilder b = new StringBuilder(128);
4317 b.append("restoreSome token=");
4318 b.append(Long.toHexString(token));
4319 b.append(" observer=");
4320 b.append(observer.toString());
4321 b.append(" packages=");
4322 if (packages == null) {
4323 b.append("null");
4324 } else {
4325 b.append('{');
4326 boolean first = true;
4327 for (String s : packages) {
4328 if (!first) {
4329 b.append(", ");
4330 } else first = false;
4331 b.append(s);
4332 }
4333 b.append('}');
4334 }
4335 Slog.d(TAG, b.toString());
4336 }
4337
4338 if (mEnded) {
4339 throw new IllegalStateException("Restore session already ended");
4340 }
4341
4342 if (mRestoreTransport == null || mRestoreSets == null) {
4343 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
4344 return -1;
4345 }
4346
4347 if (mPackageName != null) {
4348 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
4349 return -1;
4350 }
4351
4352 synchronized (mQueueLock) {
4353 for (int i = 0; i < mRestoreSets.length; i++) {
4354 if (token == mRestoreSets[i].token) {
4355 long oldId = Binder.clearCallingIdentity();
4356 mWakelock.acquire();
4357 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
4358 msg.obj = new RestoreParams(mRestoreTransport, observer, token,
4359 packages, true);
4360 mBackupHandler.sendMessage(msg);
4361 Binder.restoreCallingIdentity(oldId);
4362 return 0;
4363 }
4364 }
4365 }
4366
4367 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
4368 return -1;
4369 }
4370
Christopher Tate84725812010-02-04 15:52:40 -08004371 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004372 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08004373
Christopher Tate73a3cb32010-12-13 18:27:26 -08004374 if (mEnded) {
4375 throw new IllegalStateException("Restore session already ended");
4376 }
4377
Chris Tate44ab8452010-11-16 15:10:49 -08004378 if (mPackageName != null) {
4379 if (! mPackageName.equals(packageName)) {
4380 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
4381 + " on session for package " + mPackageName);
4382 return -1;
4383 }
4384 }
4385
Christopher Tate84725812010-02-04 15:52:40 -08004386 PackageInfo app = null;
4387 try {
4388 app = mPackageManager.getPackageInfo(packageName, 0);
4389 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004390 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08004391 return -1;
4392 }
4393
4394 // If the caller is not privileged and is not coming from the target
4395 // app's uid, throw a permission exception back to the caller.
4396 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
4397 Binder.getCallingPid(), Binder.getCallingUid());
4398 if ((perm == PackageManager.PERMISSION_DENIED) &&
4399 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004400 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08004401 + " or calling uid=" + Binder.getCallingUid());
4402 throw new SecurityException("No permission to restore other packages");
4403 }
4404
Christopher Tate7d411a32010-02-26 11:27:08 -08004405 // If the package has no backup agent, we obviously cannot proceed
4406 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004407 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08004408 return -1;
4409 }
4410
Christopher Tate84725812010-02-04 15:52:40 -08004411 // So far so good; we're allowed to try to restore this package. Now
4412 // check whether there is data for it in the current dataset, falling back
4413 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08004414 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08004415
4416 // If we didn't come up with a place to look -- no ancestral dataset and
4417 // the app has never been backed up from this device -- there's nothing
4418 // to do but return failure.
4419 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08004420 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08004421 return -1;
4422 }
4423
4424 // Ready to go: enqueue the restore request and claim success
4425 long oldId = Binder.clearCallingIdentity();
4426 mWakelock.acquire();
4427 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07004428 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08004429 mBackupHandler.sendMessage(msg);
4430 Binder.restoreCallingIdentity(oldId);
4431 return 0;
4432 }
4433
Christopher Tate73a3cb32010-12-13 18:27:26 -08004434 // Posted to the handler to tear down a restore session in a cleanly synchronized way
4435 class EndRestoreRunnable implements Runnable {
4436 BackupManagerService mBackupManager;
4437 ActiveRestoreSession mSession;
4438
4439 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
4440 mBackupManager = manager;
4441 mSession = session;
4442 }
4443
4444 public void run() {
4445 // clean up the session's bookkeeping
4446 synchronized (mSession) {
4447 try {
4448 if (mSession.mRestoreTransport != null) {
4449 mSession.mRestoreTransport.finishRestore();
4450 }
4451 } catch (Exception e) {
4452 Slog.e(TAG, "Error in finishRestore", e);
4453 } finally {
4454 mSession.mRestoreTransport = null;
4455 mSession.mEnded = true;
4456 }
4457 }
4458
4459 // clean up the BackupManagerService side of the bookkeeping
4460 // and cancel any pending timeout message
4461 mBackupManager.clearRestoreSession(mSession);
4462 }
4463 }
4464
Dan Egnor0084da52009-07-29 12:57:16 -07004465 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004466 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04004467
Christopher Tate73a3cb32010-12-13 18:27:26 -08004468 if (mEnded) {
4469 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07004470 }
4471
Christopher Tate73a3cb32010-12-13 18:27:26 -08004472 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07004473 }
4474 }
4475
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004476 @Override
4477 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004478 long identityToken = Binder.clearCallingIdentity();
4479 try {
4480 dumpInternal(pw);
4481 } finally {
4482 Binder.restoreCallingIdentity(identityToken);
4483 }
4484 }
4485
4486 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004487 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07004488 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07004489 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08004490 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08004491 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07004492 pw.println("Last backup pass: " + mLastBackupPass
4493 + " (now = " + System.currentTimeMillis() + ')');
4494 pw.println(" next scheduled: " + mNextBackupPass);
4495
Christopher Tate91717492009-06-26 21:07:13 -07004496 pw.println("Available transports:");
4497 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07004498 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
4499 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004500 IBackupTransport transport = getTransport(t);
4501 File dir = new File(mBaseStateDir, transport.transportDirName());
4502 pw.println(" destination: " + transport.currentDestinationString());
4503 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07004504 for (File f : dir.listFiles()) {
4505 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
4506 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08004507 } catch (Exception e) {
4508 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07004509 pw.println(" Error: " + e);
4510 }
Christopher Tate91717492009-06-26 21:07:13 -07004511 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004512
4513 pw.println("Pending init: " + mPendingInits.size());
4514 for (String s : mPendingInits) {
4515 pw.println(" " + s);
4516 }
4517
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004518 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07004519 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004520 for (int i=0; i<N; i++) {
4521 int uid = mBackupParticipants.keyAt(i);
4522 pw.print(" uid: ");
4523 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004524 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
4525 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07004526 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004527 }
4528 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004529
Christopher Tateb49ceb32010-02-08 16:22:24 -08004530 pw.println("Ancestral packages: "
4531 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07004532 if (mAncestralPackages != null) {
4533 for (String pkg : mAncestralPackages) {
4534 pw.println(" " + pkg);
4535 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08004536 }
4537
Christopher Tate73e02522009-07-15 14:18:26 -07004538 pw.println("Ever backed up: " + mEverStoredApps.size());
4539 for (String pkg : mEverStoredApps) {
4540 pw.println(" " + pkg);
4541 }
Christopher Tate55f931a2009-09-29 17:17:34 -07004542
4543 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07004544 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07004545 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07004546 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07004547 }
4548 }
Christopher Tate487529a2009-04-29 14:03:25 -07004549}