blob: 77c2a442870ce9a2265ed21d0dc8a293cda3e51f [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 Tate4a627c72011-04-01 14:43:32 -070026import android.app.backup.BackupDataOutput;
27import android.app.backup.FullBackup;
Jason parksa3cdaa52011-01-13 14:15:43 -060028import android.app.backup.RestoreSet;
Christopher Tate45281862010-03-05 15:46:30 -080029import android.app.backup.IBackupManager;
Christopher Tate4a627c72011-04-01 14:43:32 -070030import android.app.backup.IFullBackupRestoreObserver;
Christopher Tate45281862010-03-05 15:46:30 -080031import android.app.backup.IRestoreObserver;
32import android.app.backup.IRestoreSession;
Christopher Tate4a627c72011-04-01 14:43:32 -070033import android.content.ActivityNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070036import android.content.Context;
37import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070038import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070039import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070040import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070041import android.content.pm.IPackageDataObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080042import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070043import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070044import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060045import android.content.pm.Signature;
Jason parksa3cdaa52011-01-13 14:15:43 -060046import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070047import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070049import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070050import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080052import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070053import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080054import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070056import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070057import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070058import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070059import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070060import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070061import android.os.WorkSource;
Oscar Montemayora8529f62009-11-18 10:14:20 -080062import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070063import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080064import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070065import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080066import android.util.SparseIntArray;
Christopher Tate4a627c72011-04-01 14:43:32 -070067import android.util.StringBuilderPrinter;
68
69import libcore.io.Libcore;
Christopher Tate487529a2009-04-29 14:03:25 -070070
Jason parksa3cdaa52011-01-13 14:15:43 -060071import com.android.internal.backup.BackupConstants;
72import com.android.internal.backup.IBackupTransport;
73import com.android.internal.backup.LocalTransport;
74import com.android.server.PackageManagerBackupAgent.Metadata;
75
Christopher Tatecde87f42009-06-12 12:55:53 -070076import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070077import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070078import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080079import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070080import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070081import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070082import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070083import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040084import java.util.ArrayList;
85import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070086import java.util.HashSet;
87import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070088import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070089import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080090import java.util.Set;
Christopher Tate4a627c72011-04-01 14:43:32 -070091import java.util.concurrent.atomic.AtomicBoolean;
Christopher Tate487529a2009-04-29 14:03:25 -070092
93class BackupManagerService extends IBackupManager.Stub {
94 private static final String TAG = "BackupManagerService";
Christopher Tate4a627c72011-04-01 14:43:32 -070095 private static final boolean DEBUG = true;
96
97 // Name and current contents version of the full-backup manifest file
98 static final String BACKUP_MANIFEST_FILENAME = "_manifest";
99 static final int BACKUP_MANIFEST_VERSION = 1;
Christopher Tateaa088442009-06-16 18:25:46 -0700100
Christopher Tate49401dd2009-07-01 12:34:29 -0700101 // How often we perform a backup pass. Privileged external callers can
102 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -0700103 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -0700104
Dan Egnorc1c49c02009-10-30 17:35:39 -0700105 // Random variation in backup scheduling time to avoid server load spikes
106 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
107
Christopher Tate8031a3d2009-07-06 16:36:05 -0700108 // The amount of time between the initial provisioning of the device and
109 // the first backup pass.
110 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
111
Christopher Tate45281862010-03-05 15:46:30 -0800112 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
113 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
114 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700115 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700116 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700117 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700118 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700119 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700120 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
121 private static final int MSG_TIMEOUT = 7;
Christopher Tate73a3cb32010-12-13 18:27:26 -0800122 private static final int MSG_RESTORE_TIMEOUT = 8;
Christopher Tate4a627c72011-04-01 14:43:32 -0700123 private static final int MSG_FULL_CONFIRMATION_TIMEOUT = 9;
124 private static final int MSG_RUN_FULL_RESTORE = 10;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700125
126 // Timeout interval for deciding that a bind or clear-data has taken too long
127 static final long TIMEOUT_INTERVAL = 10 * 1000;
128
Christopher Tate44a27902010-01-27 17:15:49 -0800129 // Timeout intervals for agent backup & restore operations
130 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
Christopher Tate4a627c72011-04-01 14:43:32 -0700131 static final long TIMEOUT_FULL_BACKUP_INTERVAL = 5 * 60 * 1000;
Christopher Tate44a27902010-01-27 17:15:49 -0800132 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
133
Christopher Tate4a627c72011-04-01 14:43:32 -0700134 // User confirmation timeout for a full backup/restore operation
135 static final long TIMEOUT_FULL_CONFIRMATION = 30 * 1000;
136
Christopher Tate487529a2009-04-29 14:03:25 -0700137 private Context mContext;
138 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800139 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700140 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700141 private PowerManager mPowerManager;
142 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800143 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700144
Christopher Tate73e02522009-07-15 14:18:26 -0700145 boolean mEnabled; // access to this is synchronized on 'this'
146 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800147 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700148 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800149 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
150 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700151 PendingIntent mRunBackupIntent, mRunInitIntent;
152 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700153 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700154 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700155 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700156 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700157 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700158 public ApplicationInfo appInfo;
Christopher Tateaa088442009-06-16 18:25:46 -0700159
Christopher Tate4a627c72011-04-01 14:43:32 -0700160 BackupRequest(ApplicationInfo app) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700161 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700162 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700163
164 public String toString() {
Christopher Tate4a627c72011-04-01 14:43:32 -0700165 return "BackupRequest{app=" + appInfo + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700166 }
Christopher Tate46758122009-05-06 11:22:00 -0700167 }
Christopher Tatec28083a2010-12-14 16:16:44 -0800168 // Backups that we haven't started yet. Keys are package names.
169 HashMap<String,BackupRequest> mPendingBackups
170 = new HashMap<String,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700171
172 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700173 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700174
175 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700176 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700177
Christopher Tate043dadc2009-06-02 16:11:00 -0700178 // The thread performing the sequence of queued backups binds to each app's agent
179 // in succession. Bind notifications are asynchronously delivered through the
180 // Activity Manager; use this lock object to signal when a requested binding has
181 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700182 final Object mAgentConnectLock = new Object();
183 IBackupAgent mConnectedAgent;
184 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700185 volatile long mLastBackupPass;
186 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700187
Christopher Tate55f931a2009-09-29 17:17:34 -0700188 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700189 final Object mClearDataLock = new Object();
190 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700191
Christopher Tate91717492009-06-26 21:07:13 -0700192 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700193 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700194 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700195 String mCurrentTransport;
196 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800197 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700198
Christopher Tate2d449afe2010-03-29 19:14:24 -0700199 class RestoreGetSetsParams {
200 public IBackupTransport transport;
201 public ActiveRestoreSession session;
202 public IRestoreObserver observer;
203
204 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
205 IRestoreObserver _observer) {
206 transport = _transport;
207 session = _session;
208 observer = _observer;
209 }
210 }
211
Christopher Tate73e02522009-07-15 14:18:26 -0700212 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700213 public IBackupTransport transport;
214 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700215 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800216 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800217 public int pmToken; // in post-install restore, the PM's token for this transaction
Chris Tate249345b2010-10-29 12:57:04 -0700218 public boolean needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800219
220 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Chris Tate249345b2010-10-29 12:57:04 -0700221 long _token, PackageInfo _pkg, int _pmToken, boolean _needFullBackup) {
Christopher Tate84725812010-02-04 15:52:40 -0800222 transport = _transport;
223 observer = _obs;
224 token = _token;
225 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800226 pmToken = _pmToken;
Chris Tate249345b2010-10-29 12:57:04 -0700227 needFullBackup = _needFullBackup;
Christopher Tate84725812010-02-04 15:52:40 -0800228 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700229
Chris Tate249345b2010-10-29 12:57:04 -0700230 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token,
231 boolean _needFullBackup) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700232 transport = _transport;
233 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700234 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800235 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800236 pmToken = 0;
Chris Tate249345b2010-10-29 12:57:04 -0700237 needFullBackup = _needFullBackup;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700238 }
239 }
240
Christopher Tate73e02522009-07-15 14:18:26 -0700241 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700242 public IBackupTransport transport;
243 public PackageInfo packageInfo;
244
245 ClearParams(IBackupTransport _transport, PackageInfo _info) {
246 transport = _transport;
247 packageInfo = _info;
248 }
249 }
250
Christopher Tate4a627c72011-04-01 14:43:32 -0700251 class FullParams {
252 public ParcelFileDescriptor fd;
253 public final AtomicBoolean latch;
254 public IFullBackupRestoreObserver observer;
255
256 FullParams() {
257 latch = new AtomicBoolean(false);
258 }
259 }
260
261 class FullBackupParams extends FullParams {
262 public boolean includeApks;
263 public boolean includeShared;
264 public boolean allApps;
265 public String[] packages;
266
267 FullBackupParams(ParcelFileDescriptor output, boolean saveApks, boolean saveShared,
268 boolean doAllApps, String[] pkgList) {
269 fd = output;
270 includeApks = saveApks;
271 includeShared = saveShared;
272 allApps = doAllApps;
273 packages = pkgList;
274 }
275 }
276
277 class FullRestoreParams extends FullParams {
278 FullRestoreParams(ParcelFileDescriptor input) {
279 fd = input;
280 }
281 }
282
Christopher Tate44a27902010-01-27 17:15:49 -0800283 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
284 // token is the index of the entry in the pending-operations list.
285 static final int OP_PENDING = 0;
286 static final int OP_ACKNOWLEDGED = 1;
287 static final int OP_TIMEOUT = -1;
288
289 final SparseIntArray mCurrentOperations = new SparseIntArray();
290 final Object mCurrentOpLock = new Object();
291 final Random mTokenGenerator = new Random();
292
Christopher Tate4a627c72011-04-01 14:43:32 -0700293 final SparseArray<FullParams> mFullConfirmations = new SparseArray<FullParams>();
294
Christopher Tate5cb400b2009-06-25 16:03:14 -0700295 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700296 File mBaseStateDir;
297 File mDataDir;
298 File mJournalDir;
299 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700300
Christopher Tate84725812010-02-04 15:52:40 -0800301 // Keep a log of all the apps we've ever backed up, and what the
302 // dataset tokens are for both the current backup dataset and
303 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700304 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700305 HashSet<String> mEverStoredApps = new HashSet<String>();
306
Christopher Tateb49ceb32010-02-08 16:22:24 -0800307 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800308 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800309 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800310 long mAncestralToken = 0;
311 long mCurrentToken = 0;
312
Christopher Tate4cc86e12009-09-21 19:36:51 -0700313 // Persistently track the need to do a full init
314 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
315 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700316
Christopher Tate4a627c72011-04-01 14:43:32 -0700317 // Utility: build a new random integer token
318 int generateToken() {
319 int token;
320 do {
321 synchronized (mTokenGenerator) {
322 token = mTokenGenerator.nextInt();
323 }
324 } while (token < 0);
325 return token;
326 }
327
Christopher Tate44a27902010-01-27 17:15:49 -0800328 // ----- Asynchronous backup/restore handler thread -----
329
330 private class BackupHandler extends Handler {
331 public BackupHandler(Looper looper) {
332 super(looper);
333 }
334
335 public void handleMessage(Message msg) {
336
337 switch (msg.what) {
338 case MSG_RUN_BACKUP:
339 {
340 mLastBackupPass = System.currentTimeMillis();
341 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
342
343 IBackupTransport transport = getTransport(mCurrentTransport);
344 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800345 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800346 mWakelock.release();
347 break;
348 }
349
350 // snapshot the pending-backup set and work on that
351 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800352 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800353 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800354 // Do we have any work to do? Construct the work queue
355 // then release the synchronization lock to actually run
356 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800357 if (mPendingBackups.size() > 0) {
358 for (BackupRequest b: mPendingBackups.values()) {
359 queue.add(b);
360 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800361 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800362 mPendingBackups.clear();
363
364 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800365 mJournal = null;
366
Christopher Tate44a27902010-01-27 17:15:49 -0800367 }
368 }
Christopher Tatec61da312010-02-05 10:41:27 -0800369
370 if (queue.size() > 0) {
371 // At this point, we have started a new journal file, and the old
372 // file identity is being passed to the backup processing thread.
373 // When it completes successfully, that old journal file will be
374 // deleted. If we crash prior to that, the old journal is parsed
375 // at next boot and the journaled requests fulfilled.
376 (new PerformBackupTask(transport, queue, oldJournal)).run();
377 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800378 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800379 mWakelock.release();
380 }
Christopher Tate44a27902010-01-27 17:15:49 -0800381 break;
382 }
383
384 case MSG_RUN_FULL_BACKUP:
Christopher Tate4a627c72011-04-01 14:43:32 -0700385 {
386 FullBackupParams params = (FullBackupParams)msg.obj;
387 (new PerformFullBackupTask(params.fd, params.observer, params.includeApks,
388 params.includeShared, params.allApps, params.packages,
389 params.latch)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800390 break;
Christopher Tate4a627c72011-04-01 14:43:32 -0700391 }
Christopher Tate44a27902010-01-27 17:15:49 -0800392
393 case MSG_RUN_RESTORE:
394 {
395 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800396 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800397 (new PerformRestoreTask(params.transport, params.observer,
Chris Tate249345b2010-10-29 12:57:04 -0700398 params.token, params.pkgInfo, params.pmToken,
399 params.needFullBackup)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800400 break;
401 }
402
403 case MSG_RUN_CLEAR:
404 {
405 ClearParams params = (ClearParams)msg.obj;
406 (new PerformClearTask(params.transport, params.packageInfo)).run();
407 break;
408 }
409
410 case MSG_RUN_INITIALIZE:
411 {
412 HashSet<String> queue;
413
414 // Snapshot the pending-init queue and work on that
415 synchronized (mQueueLock) {
416 queue = new HashSet<String>(mPendingInits);
417 mPendingInits.clear();
418 }
419
420 (new PerformInitializeTask(queue)).run();
421 break;
422 }
423
Christopher Tate2d449afe2010-03-29 19:14:24 -0700424 case MSG_RUN_GET_RESTORE_SETS:
425 {
426 // Like other async operations, this is entered with the wakelock held
427 RestoreSet[] sets = null;
428 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
429 try {
430 sets = params.transport.getAvailableRestoreSets();
431 // cache the result in the active session
432 synchronized (params.session) {
433 params.session.mRestoreSets = sets;
434 }
435 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
436 } catch (Exception e) {
437 Slog.e(TAG, "Error from transport getting set list");
438 } finally {
439 if (params.observer != null) {
440 try {
441 params.observer.restoreSetsAvailable(sets);
442 } catch (RemoteException re) {
443 Slog.e(TAG, "Unable to report listing to observer");
444 } catch (Exception e) {
445 Slog.e(TAG, "Restore observer threw", e);
446 }
447 }
448
Christopher Tate2a935092011-03-03 17:30:32 -0800449 // Done: reset the session timeout clock
450 removeMessages(MSG_RESTORE_TIMEOUT);
451 sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
452
Christopher Tate2d449afe2010-03-29 19:14:24 -0700453 mWakelock.release();
454 }
455 break;
456 }
457
Christopher Tate44a27902010-01-27 17:15:49 -0800458 case MSG_TIMEOUT:
459 {
460 synchronized (mCurrentOpLock) {
461 final int token = msg.arg1;
462 int state = mCurrentOperations.get(token, OP_TIMEOUT);
463 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800464 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800465 mCurrentOperations.put(token, OP_TIMEOUT);
466 }
467 mCurrentOpLock.notifyAll();
468 }
469 break;
470 }
Christopher Tate73a3cb32010-12-13 18:27:26 -0800471
472 case MSG_RESTORE_TIMEOUT:
473 {
474 synchronized (BackupManagerService.this) {
475 if (mActiveRestoreSession != null) {
476 // Client app left the restore session dangling. We know that it
477 // can't be in the middle of an actual restore operation because
478 // those are executed serially on this same handler thread. Clean
479 // up now.
480 Slog.w(TAG, "Restore session timed out; aborting");
481 post(mActiveRestoreSession.new EndRestoreRunnable(
482 BackupManagerService.this, mActiveRestoreSession));
483 }
484 }
485 }
Christopher Tate4a627c72011-04-01 14:43:32 -0700486
487 case MSG_FULL_CONFIRMATION_TIMEOUT:
488 {
489 synchronized (mFullConfirmations) {
490 FullParams params = mFullConfirmations.get(msg.arg1);
491 if (params != null) {
492 Slog.i(TAG, "Full backup/restore timed out waiting for user confirmation");
493
494 // Release the waiter; timeout == completion
495 signalFullBackupRestoreCompletion(params);
496
497 // Remove the token from the set
498 mFullConfirmations.delete(msg.arg1);
499
500 // Report a timeout to the observer, if any
501 if (params.observer != null) {
502 try {
503 params.observer.onTimeout();
504 } catch (RemoteException e) {
505 /* don't care if the app has gone away */
506 }
507 }
508 } else {
509 Slog.d(TAG, "couldn't find params for token " + msg.arg1);
510 }
511 }
512 break;
513 }
Christopher Tate44a27902010-01-27 17:15:49 -0800514 }
515 }
516 }
517
518 // ----- Main service implementation -----
519
Christopher Tate487529a2009-04-29 14:03:25 -0700520 public BackupManagerService(Context context) {
521 mContext = context;
522 mPackageManager = context.getPackageManager();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700523 mPackageManagerBinder = AppGlobals.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700524 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700525
Christopher Tateb6787f22009-07-02 17:40:45 -0700526 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
527 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
528
Christopher Tate44a27902010-01-27 17:15:49 -0800529 mBackupManagerBinder = asInterface(asBinder());
530
531 // spin up the backup/restore handler thread
532 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
533 mHandlerThread.start();
534 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
535
Christopher Tate22b87872009-05-04 16:41:53 -0700536 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700537 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700538 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700539 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700540 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800541 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800542 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800543 // If Encrypted file systems is enabled or disabled, this call will return the
544 // correct directory.
Jason parksa3cdaa52011-01-13 14:15:43 -0600545 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800546 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700547 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700548
Christopher Tate4cc86e12009-09-21 19:36:51 -0700549 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700550 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700551 IntentFilter filter = new IntentFilter();
552 filter.addAction(RUN_BACKUP_ACTION);
553 context.registerReceiver(mRunBackupReceiver, filter,
554 android.Manifest.permission.BACKUP, null);
555
556 mRunInitReceiver = new RunInitializeReceiver();
557 filter = new IntentFilter();
558 filter.addAction(RUN_INITIALIZE_ACTION);
559 context.registerReceiver(mRunInitReceiver, filter,
560 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700561
562 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700563 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
564 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
565
Christopher Tate4cc86e12009-09-21 19:36:51 -0700566 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
567 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
568 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
569
Christopher Tatecde87f42009-06-12 12:55:53 -0700570 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700571 mJournalDir = new File(mBaseStateDir, "pending");
572 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700573 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700574
Christopher Tate73e02522009-07-15 14:18:26 -0700575 // Set up the various sorts of package tracking we do
576 initPackageTracking();
577
Christopher Tateabce4e82009-06-18 18:35:32 -0700578 // Build our mapping of uid to backup client services. This implicitly
579 // schedules a backup pass on the Package Manager metadata the first
580 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700581 synchronized (mBackupParticipants) {
582 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700583 }
584
Dan Egnor87a02bc2009-06-17 02:30:10 -0700585 // Set up our transport options and initialize the default transport
586 // TODO: Have transports register themselves somehow?
587 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700588 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700589 ComponentName localName = new ComponentName(context, LocalTransport.class);
590 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700591
Christopher Tate91717492009-06-26 21:07:13 -0700592 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700593 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
594 Settings.Secure.BACKUP_TRANSPORT);
595 if ("".equals(mCurrentTransport)) {
596 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700597 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800598 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700599
600 // Attach to the Google backup transport. When this comes up, it will set
601 // itself as the current transport because we explicitly reset mCurrentTransport
602 // to null.
Christopher Tatea32504f2010-04-21 17:58:07 -0700603 ComponentName transportComponent = new ComponentName("com.google.android.backup",
604 "com.google.android.backup.BackupTransportService");
605 try {
606 // If there's something out there that is supposed to be the Google
607 // backup transport, make sure it's legitimately part of the OS build
608 // and not an app lying about its package name.
609 ApplicationInfo info = mPackageManager.getApplicationInfo(
610 transportComponent.getPackageName(), 0);
611 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
612 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
613 Intent intent = new Intent().setComponent(transportComponent);
614 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
615 } else {
616 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
617 }
618 } catch (PackageManager.NameNotFoundException nnf) {
619 // No such package? No binding.
620 if (DEBUG) Slog.v(TAG, "Google transport not present");
621 }
Christopher Tateaa088442009-06-16 18:25:46 -0700622
Christopher Tatecde87f42009-06-12 12:55:53 -0700623 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700624 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700625 parseLeftoverJournals();
626
Christopher Tateb6787f22009-07-02 17:40:45 -0700627 // Power management
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700628 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*backup*");
Christopher Tateb6787f22009-07-02 17:40:45 -0700629
630 // Start the backup passes going
631 setBackupEnabled(areEnabled);
632 }
633
634 private class RunBackupReceiver extends BroadcastReceiver {
635 public void onReceive(Context context, Intent intent) {
636 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700637 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700638 if (mPendingInits.size() > 0) {
639 // If there are pending init operations, we process those
640 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800641 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700642 try {
643 mAlarmManager.cancel(mRunInitIntent);
644 mRunInitIntent.send();
645 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800646 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700647 // can't really do more than bail here
648 }
649 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800650 // Don't run backups now if we're disabled or not yet
651 // fully set up.
652 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800653 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700654
655 // Acquire the wakelock and pass it to the backup thread. it will
656 // be released once backup concludes.
657 mWakelock.acquire();
658
659 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
660 mBackupHandler.sendMessage(msg);
661 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800662 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700663 }
664 }
665 }
666 }
667 }
668 }
669
670 private class RunInitializeReceiver extends BroadcastReceiver {
671 public void onReceive(Context context, Intent intent) {
672 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
673 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800674 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700675
676 // Acquire the wakelock and pass it to the init thread. it will
677 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700678 mWakelock.acquire();
679
Christopher Tate4cc86e12009-09-21 19:36:51 -0700680 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700681 mBackupHandler.sendMessage(msg);
682 }
683 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700684 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700685 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700686
Christopher Tate73e02522009-07-15 14:18:26 -0700687 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800688 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700689
Christopher Tate84725812010-02-04 15:52:40 -0800690 // Remember our ancestral dataset
691 mTokenFile = new File(mBaseStateDir, "ancestral");
692 try {
693 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800694 int version = tf.readInt();
695 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
696 mAncestralToken = tf.readLong();
697 mCurrentToken = tf.readLong();
698
699 int numPackages = tf.readInt();
700 if (numPackages >= 0) {
701 mAncestralPackages = new HashSet<String>();
702 for (int i = 0; i < numPackages; i++) {
703 String pkgName = tf.readUTF();
704 mAncestralPackages.add(pkgName);
705 }
706 }
707 }
Brad Fitzpatrick725d8f02010-11-15 11:12:42 -0800708 tf.close();
Christopher Tate1168baa2010-02-17 13:03:40 -0800709 } catch (FileNotFoundException fnf) {
710 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800711 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800712 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800713 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800714 }
715
Christopher Tatee97e8072009-07-15 16:45:50 -0700716 // Keep a log of what apps we've ever backed up. Because we might have
717 // rebooted in the middle of an operation that was removing something from
718 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700719 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700720 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700721
Christopher Tatee97e8072009-07-15 16:45:50 -0700722 // If we were in the middle of removing something from the ever-backed-up
723 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700724 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700725 if (tempProcessedFile.exists()) {
726 tempProcessedFile.delete();
727 }
728
Dan Egnor852f8e42009-09-30 11:20:45 -0700729 // If there are previous contents, parse them out then start a new
730 // file to continue the recordkeeping.
731 if (mEverStored.exists()) {
732 RandomAccessFile temp = null;
733 RandomAccessFile in = null;
734
735 try {
736 temp = new RandomAccessFile(tempProcessedFile, "rws");
737 in = new RandomAccessFile(mEverStored, "r");
738
739 while (true) {
740 PackageInfo info;
741 String pkg = in.readUTF();
742 try {
743 info = mPackageManager.getPackageInfo(pkg, 0);
744 mEverStoredApps.add(pkg);
745 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800746 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700747 } catch (NameNotFoundException e) {
748 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800749 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700750 }
751 }
752 } catch (EOFException e) {
753 // Once we've rewritten the backup history log, atomically replace the
754 // old one with the new one then reopen the file for continuing use.
755 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800756 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700757 }
758 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800759 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700760 } finally {
761 try { if (temp != null) temp.close(); } catch (IOException e) {}
762 try { if (in != null) in.close(); } catch (IOException e) {}
763 }
764 }
765
Christopher Tate73e02522009-07-15 14:18:26 -0700766 // Register for broadcasts about package install, etc., so we can
767 // update the provider list.
768 IntentFilter filter = new IntentFilter();
769 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
770 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
771 filter.addDataScheme("package");
772 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800773 // Register for events related to sdcard installation.
774 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800775 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
776 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800777 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700778 }
779
Christopher Tatecde87f42009-06-12 12:55:53 -0700780 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700781 for (File f : mJournalDir.listFiles()) {
782 if (mJournal == null || f.compareTo(mJournal) != 0) {
783 // This isn't the current journal, so it must be a leftover. Read
784 // out the package names mentioned there and schedule them for
785 // backup.
786 RandomAccessFile in = null;
787 try {
Joe Onorato431bb222010-10-18 19:13:23 -0400788 Slog.i(TAG, "Found stale backup journal, scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700789 in = new RandomAccessFile(f, "r");
790 while (true) {
791 String packageName = in.readUTF();
Joe Onorato431bb222010-10-18 19:13:23 -0400792 Slog.i(TAG, " " + packageName);
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -0700793 dataChangedImpl(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700794 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700795 } catch (EOFException e) {
796 // no more data; we're done
797 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800798 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700799 } finally {
800 // close/delete the file
801 try { if (in != null) in.close(); } catch (IOException e) {}
802 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700803 }
804 }
805 }
806 }
807
Christopher Tate4cc86e12009-09-21 19:36:51 -0700808 // Maintain persistent state around whether need to do an initialize operation.
809 // Must be called with the queue lock held.
810 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800811 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700812 + " on transport " + transportName);
813 try {
814 IBackupTransport transport = getTransport(transportName);
815 String transportDirName = transport.transportDirName();
816 File stateDir = new File(mBaseStateDir, transportDirName);
817 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
818
819 if (isPending) {
820 // We need an init before we can proceed with sending backup data.
821 // Record that with an entry in our set of pending inits, as well as
822 // journaling it via creation of a sentinel file.
823 mPendingInits.add(transportName);
824 try {
825 (new FileOutputStream(initPendingFile)).close();
826 } catch (IOException ioe) {
827 // Something is badly wrong with our permissions; just try to move on
828 }
829 } else {
830 // No more initialization needed; wipe the journal and reset our state.
831 initPendingFile.delete();
832 mPendingInits.remove(transportName);
833 }
834 } catch (RemoteException e) {
835 // can't happen; the transport is local
836 }
837 }
838
Christopher Tated55e18a2009-09-21 10:12:59 -0700839 // Reset all of our bookkeeping, in response to having been told that
840 // the backend data has been wiped [due to idle expiry, for example],
841 // so we must re-upload all saved settings.
842 void resetBackupState(File stateFileDir) {
843 synchronized (mQueueLock) {
844 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700845 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700846 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700847
Christopher Tate84725812010-02-04 15:52:40 -0800848 mCurrentToken = 0;
849 writeRestoreTokens();
850
Christopher Tated55e18a2009-09-21 10:12:59 -0700851 // Remove all the state files
852 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700853 // ... but don't touch the needs-init sentinel
854 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
855 sf.delete();
856 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700857 }
Christopher Tate45597642011-04-04 16:59:21 -0700858 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700859
Christopher Tate45597642011-04-04 16:59:21 -0700860 // Enqueue a new backup of every participant
861 int N = mBackupParticipants.size();
862 for (int i=0; i<N; i++) {
863 int uid = mBackupParticipants.keyAt(i);
864 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
865 for (ApplicationInfo app: participants) {
866 dataChangedImpl(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700867 }
868 }
869 }
870
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800871 // Add a transport to our set of available backends. If 'transport' is null, this
872 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700873 private void registerTransport(String name, IBackupTransport transport) {
874 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800875 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800876 if (transport != null) {
877 mTransports.put(name, transport);
878 } else {
879 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800880 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800881 mCurrentTransport = null;
882 }
883 // Nothing further to do in the unregistration case
884 return;
885 }
Christopher Tate91717492009-06-26 21:07:13 -0700886 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700887
888 // If the init sentinel file exists, we need to be sure to perform the init
889 // as soon as practical. We also create the state directory at registration
890 // time to ensure it's present from the outset.
891 try {
892 String transportName = transport.transportDirName();
893 File stateDir = new File(mBaseStateDir, transportName);
894 stateDir.mkdirs();
895
896 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
897 if (initSentinel.exists()) {
898 synchronized (mQueueLock) {
899 mPendingInits.add(transportName);
900
901 // TODO: pick a better starting time than now + 1 minute
902 long delay = 1000 * 60; // one minute, in milliseconds
903 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
904 System.currentTimeMillis() + delay, mRunInitIntent);
905 }
906 }
907 } catch (RemoteException e) {
908 // can't happen, the transport is local
909 }
Christopher Tate91717492009-06-26 21:07:13 -0700910 }
911
Christopher Tate3799bc22009-05-06 16:13:56 -0700912 // ----- Track installation/removal of packages -----
913 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
914 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800915 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700916
Christopher Tate3799bc22009-05-06 16:13:56 -0700917 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800918 boolean replacing = false;
919 boolean added = false;
920 Bundle extras = intent.getExtras();
921 String pkgList[] = null;
922 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
923 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
924 Uri uri = intent.getData();
925 if (uri == null) {
926 return;
927 }
928 String pkgName = uri.getSchemeSpecificPart();
929 if (pkgName != null) {
930 pkgList = new String[] { pkgName };
931 }
932 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
933 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800934 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800935 added = true;
936 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800937 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800938 added = false;
939 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
940 }
941 if (pkgList == null || pkgList.length == 0) {
942 return;
943 }
944 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700945 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800946 for (String pkgName : pkgList) {
947 if (replacing) {
948 // The package was just upgraded
949 updatePackageParticipantsLocked(pkgName);
950 } else {
951 // The package was just added
952 addPackageParticipantsLocked(pkgName);
953 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700954 }
955 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800956 } else {
957 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700958 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
959 } else {
960 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800961 for (String pkgName : pkgList) {
962 removePackageParticipantsLocked(pkgName);
963 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700964 }
965 }
966 }
967 }
968 };
969
Dan Egnor87a02bc2009-06-17 02:30:10 -0700970 // ----- Track connection to GoogleBackupTransport service -----
971 ServiceConnection mGoogleConnection = new ServiceConnection() {
972 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800973 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700974 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700975 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700976 }
977
978 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800979 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700980 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700981 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700982 }
983 };
984
Christopher Tate181fafa2009-05-14 11:12:14 -0700985 // Add the backup agents in the given package to our set of known backup participants.
986 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700987 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700988 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700990 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700991 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700992 }
993
Christopher Tate181fafa2009-05-14 11:12:14 -0700994 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700995 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700996 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700998 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800999 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -07001000 + " uid=" + p.applicationInfo.uid
1001 + " killAfterRestore="
1002 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -07001003 );
Christopher Tate181fafa2009-05-14 11:12:14 -07001004 }
1005 }
1006
Dan Egnorefe52642009-06-24 00:16:33 -07001007 for (PackageInfo pkg : targetPkgs) {
1008 if (packageName == null || pkg.packageName.equals(packageName)) {
1009 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -07001010 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001011 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -07001012 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -07001013 mBackupParticipants.put(uid, set);
1014 }
Dan Egnorefe52642009-06-24 00:16:33 -07001015 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -07001016
1017 // If we've never seen this app before, schedule a backup for it
1018 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001019 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -07001020 + " never backed up; scheduling");
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001021 dataChangedImpl(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -07001022 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001023 }
Christopher Tate487529a2009-04-29 14:03:25 -07001024 }
1025 }
1026
Christopher Tate6785dd82009-06-18 15:58:25 -07001027 // Remove the given package's entry from our known active set. If
1028 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -07001029 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001030 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tatec28083a2010-12-14 16:16:44 -08001031 List<String> allApps = new ArrayList<String>();
Christopher Tate181fafa2009-05-14 11:12:14 -07001032 if (packageName != null) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001033 allApps.add(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07001034 } else {
1035 // all apps with agents
Christopher Tatec28083a2010-12-14 16:16:44 -08001036 List<PackageInfo> knownPackages = allAgentPackages();
1037 for (PackageInfo pkg : knownPackages) {
1038 allApps.add(pkg.packageName);
1039 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001040 }
1041 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001042 }
1043
Joe Onorato8ad02812009-05-13 01:41:44 -04001044 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tatec28083a2010-12-14 16:16:44 -08001045 List<String> allPackageNames) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001046 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001047 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tatec28083a2010-12-14 16:16:44 -08001048 + ") removing " + allPackageNames.size() + " entries");
1049 for (String p : allPackageNames) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001050 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -07001051 }
1052 }
Christopher Tatec28083a2010-12-14 16:16:44 -08001053 for (String pkg : allPackageNames) {
1054 if (packageName == null || pkg.equals(packageName)) {
1055 int uid = -1;
1056 try {
1057 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1058 uid = info.applicationInfo.uid;
1059 } catch (NameNotFoundException e) {
1060 // we don't know this package name, so just skip it for now
1061 continue;
1062 }
1063
Christopher Tate181fafa2009-05-14 11:12:14 -07001064 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -07001065 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001066 // Find the existing entry with the same package name, and remove it.
1067 // We can't just remove(app) because the instances are different.
1068 for (ApplicationInfo entry: set) {
Christopher Tatec28083a2010-12-14 16:16:44 -08001069 if (entry.packageName.equals(pkg)) {
1070 if (DEBUG) Slog.v(TAG, " removing participant " + pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001071 set.remove(entry);
Christopher Tatec28083a2010-12-14 16:16:44 -08001072 removeEverBackedUp(pkg);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -07001073 break;
1074 }
1075 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001076 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -07001077 mBackupParticipants.delete(uid);
1078 }
Christopher Tate3799bc22009-05-06 16:13:56 -07001079 }
1080 }
1081 }
1082 }
1083
Christopher Tate181fafa2009-05-14 11:12:14 -07001084 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -07001085 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -07001086 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -07001087 int flags = PackageManager.GET_SIGNATURES;
1088 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
1089 int N = packages.size();
1090 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -07001091 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001092 try {
1093 ApplicationInfo app = pkg.applicationInfo;
1094 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -08001095 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -07001096 packages.remove(a);
1097 }
1098 else {
1099 // we will need the shared library path, so look that up and store it here
1100 app = mPackageManager.getApplicationInfo(pkg.packageName,
1101 PackageManager.GET_SHARED_LIBRARY_FILES);
1102 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
1103 }
1104 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001105 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -07001106 }
1107 }
Dan Egnorefe52642009-06-24 00:16:33 -07001108 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -07001109 }
Christopher Tateaa088442009-06-16 18:25:46 -07001110
Christopher Tate3799bc22009-05-06 16:13:56 -07001111 // Reset the given package's known backup participants. Unlike add/remove, the update
1112 // action cannot be passed a null package name.
1113 void updatePackageParticipantsLocked(String packageName) {
1114 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001115 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -07001116 return;
1117 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001118 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -07001119
1120 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -07001121 List<PackageInfo> allApps = allAgentPackages();
Christopher Tatec28083a2010-12-14 16:16:44 -08001122 List<String> allAppNames = new ArrayList<String>();
1123 for (PackageInfo pkg : allApps) {
1124 allAppNames.add(pkg.packageName);
1125 }
1126 removePackageParticipantsLockedInner(packageName, allAppNames);
Christopher Tate181fafa2009-05-14 11:12:14 -07001127 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -07001128 }
1129
Christopher Tate84725812010-02-04 15:52:40 -08001130 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -07001131 // backed up at least once
1132 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001133 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1134
1135 synchronized (mEverStoredApps) {
1136 if (!mEverStoredApps.add(packageName)) return;
1137
1138 RandomAccessFile out = null;
1139 try {
1140 out = new RandomAccessFile(mEverStored, "rws");
1141 out.seek(out.length());
1142 out.writeUTF(packageName);
1143 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001144 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001145 } finally {
1146 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001147 }
1148 }
1149 }
1150
Christopher Tatee97e8072009-07-15 16:45:50 -07001151 // Remove our awareness of having ever backed up the given package
1152 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001153 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001154
Dan Egnor852f8e42009-09-30 11:20:45 -07001155 synchronized (mEverStoredApps) {
1156 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1157 // we'll recognize on initialization time that the package no longer
1158 // exists and fix it up then.
1159 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1160 RandomAccessFile known = null;
1161 try {
1162 known = new RandomAccessFile(tempKnownFile, "rws");
1163 mEverStoredApps.remove(packageName);
1164 for (String s : mEverStoredApps) {
1165 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001166 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001167 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001168 known.close();
1169 known = null;
1170 if (!tempKnownFile.renameTo(mEverStored)) {
1171 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1172 }
1173 } catch (IOException e) {
1174 // Bad: we couldn't create the new copy. For safety's sake we
1175 // abandon the whole process and remove all what's-backed-up
1176 // state entirely, meaning we'll force a backup pass for every
1177 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001178 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001179 mEverStoredApps.clear();
1180 tempKnownFile.delete();
1181 mEverStored.delete();
1182 } finally {
1183 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001184 }
1185 }
1186 }
1187
Christopher Tateb49ceb32010-02-08 16:22:24 -08001188 // Persistently record the current and ancestral backup tokens as well
1189 // as the set of packages with data [supposedly] available in the
1190 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001191 void writeRestoreTokens() {
1192 try {
1193 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001194
1195 // First, the version number of this record, for futureproofing
1196 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1197
1198 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001199 af.writeLong(mAncestralToken);
1200 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001201
1202 // Now write the set of ancestral packages
1203 if (mAncestralPackages == null) {
1204 af.writeInt(-1);
1205 } else {
1206 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001207 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001208 for (String pkgName : mAncestralPackages) {
1209 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001210 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001211 }
1212 }
Christopher Tate84725812010-02-04 15:52:40 -08001213 af.close();
1214 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001215 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001216 }
1217 }
1218
Dan Egnor87a02bc2009-06-17 02:30:10 -07001219 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001220 private IBackupTransport getTransport(String transportName) {
1221 synchronized (mTransports) {
1222 IBackupTransport transport = mTransports.get(transportName);
1223 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001224 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001225 }
1226 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001227 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001228 }
1229
Christopher Tatedf01dea2009-06-09 20:45:02 -07001230 // fire off a backup agent, blocking until it attaches or times out
1231 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1232 IBackupAgent agent = null;
1233 synchronized(mAgentConnectLock) {
1234 mConnecting = true;
1235 mConnectedAgent = null;
1236 try {
1237 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001238 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001239
1240 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001241 // only wait 10 seconds for the clear data to happen
1242 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1243 while (mConnecting && mConnectedAgent == null
1244 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001245 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001246 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001247 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001248 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001249 return null;
1250 }
1251 }
1252
1253 // if we timed out with no connect, abort and move on
1254 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001255 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001256 return null;
1257 }
1258 agent = mConnectedAgent;
1259 }
1260 } catch (RemoteException e) {
1261 // can't happen
1262 }
1263 }
1264 return agent;
1265 }
1266
Christopher Tatec7b31e32009-06-10 15:49:30 -07001267 // clear an application's data, blocking until the operation completes or times out
1268 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001269 // Don't wipe packages marked allowClearUserData=false
1270 try {
1271 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1272 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001273 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001274 + packageName);
1275 return;
1276 }
1277 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001278 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001279 return;
1280 }
1281
Christopher Tatec7b31e32009-06-10 15:49:30 -07001282 ClearDataObserver observer = new ClearDataObserver();
1283
1284 synchronized(mClearDataLock) {
1285 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001286 try {
1287 mActivityManager.clearApplicationUserData(packageName, observer);
1288 } catch (RemoteException e) {
1289 // can't happen because the activity manager is in this process
1290 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001291
1292 // only wait 10 seconds for the clear data to happen
1293 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1294 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1295 try {
1296 mClearDataLock.wait(5000);
1297 } catch (InterruptedException e) {
1298 // won't happen, but still.
1299 mClearingData = false;
1300 }
1301 }
1302 }
1303 }
1304
1305 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001306 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001307 synchronized(mClearDataLock) {
1308 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001309 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001310 }
1311 }
1312 }
1313
Christopher Tate1bb69062010-02-19 17:02:12 -08001314 // Get the restore-set token for the best-available restore set for this package:
1315 // the active set if possible, else the ancestral one. Returns zero if none available.
1316 long getAvailableRestoreToken(String packageName) {
1317 long token = mAncestralToken;
1318 synchronized (mQueueLock) {
1319 if (mEverStoredApps.contains(packageName)) {
1320 token = mCurrentToken;
1321 }
1322 }
1323 return token;
1324 }
1325
Christopher Tate44a27902010-01-27 17:15:49 -08001326 // -----
1327 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1328 boolean waitUntilOperationComplete(int token) {
1329 int finalState = OP_PENDING;
1330 synchronized (mCurrentOpLock) {
1331 try {
1332 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1333 try {
1334 mCurrentOpLock.wait();
1335 } catch (InterruptedException e) {}
1336 }
1337 } catch (IndexOutOfBoundsException e) {
1338 // the operation has been mysteriously cleared from our
1339 // bookkeeping -- consider this a success and ignore it.
1340 }
1341 }
1342 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001343 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001344 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001345 return finalState == OP_ACKNOWLEDGED;
1346 }
1347
1348 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001349 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001350 + " interval=" + interval);
Christopher Tate4a627c72011-04-01 14:43:32 -07001351 synchronized (mCurrentOpLock) {
1352 mCurrentOperations.put(token, OP_PENDING);
1353 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1354 mBackupHandler.sendMessageDelayed(msg, interval);
1355 }
Christopher Tate44a27902010-01-27 17:15:49 -08001356 }
1357
Christopher Tate043dadc2009-06-02 16:11:00 -07001358 // ----- Back up a set of applications via a worker thread -----
1359
Christopher Tate44a27902010-01-27 17:15:49 -08001360 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001361 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001362 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001363 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001364 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001365 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001366
Christopher Tate44a27902010-01-27 17:15:49 -08001367 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001368 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001369 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001370 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001371 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001372
1373 try {
1374 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1375 } catch (RemoteException e) {
1376 // can't happen; the transport is local
1377 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001378 }
1379
Christopher Tate043dadc2009-06-02 16:11:00 -07001380 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001381 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001382 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001383 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001384
Christopher Tate79588342009-06-30 16:11:49 -07001385 // Backups run at background priority
1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387
Christopher Tate043dadc2009-06-02 16:11:00 -07001388 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001389 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001390
Dan Egnor852f8e42009-09-30 11:20:45 -07001391 // If we haven't stored package manager metadata yet, we must init the transport.
1392 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1393 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001394 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001395 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001396 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001397 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001398 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001399 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001400 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001401 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001402 }
Dan Egnor01445162009-09-21 17:04:05 -07001403 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001404
1405 // The package manager doesn't have a proper <application> etc, but since
1406 // it's running here in the system process we can just set up its agent
1407 // directly and use a synthetic BackupRequest. We always run this pass
1408 // because it's cheap and this way we guarantee that we don't get out of
1409 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001410 if (status == BackupConstants.TRANSPORT_OK) {
1411 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1412 mPackageManager, allAgentPackages());
Christopher Tate4a627c72011-04-01 14:43:32 -07001413 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo());
Dan Egnor01445162009-09-21 17:04:05 -07001414 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1415 status = processOneBackup(pmRequest,
1416 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1417 }
Christopher Tate90967f42009-09-20 15:28:33 -07001418
Dan Egnor01445162009-09-21 17:04:05 -07001419 if (status == BackupConstants.TRANSPORT_OK) {
1420 // Now run all the backups in our queue
1421 status = doQueuedBackups(mTransport);
1422 }
1423
1424 if (status == BackupConstants.TRANSPORT_OK) {
1425 // Tell the transport to finish everything it has buffered
1426 status = mTransport.finishBackup();
1427 if (status == BackupConstants.TRANSPORT_OK) {
1428 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001429 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001430 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001431 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001432 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001433 }
1434 }
1435
Dan Egnor01445162009-09-21 17:04:05 -07001436 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001437 // The backend reports that our dataset has been wiped. We need to
1438 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001439 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001440 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001441 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001442 }
1443 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001444 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001445 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001446 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001447 // If everything actually went through and this is the first time we've
1448 // done a backup, we can now record what the current backup dataset token
1449 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001450 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001451 try {
1452 mCurrentToken = mTransport.getCurrentRestoreSet();
1453 } catch (RemoteException e) { /* cannot happen */ }
1454 writeRestoreTokens();
1455 }
1456
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001457 // If things went wrong, we need to re-stage the apps we had expected
1458 // to be backing up in this pass. This journals the package names in
1459 // the current active pending-backup file, not in the we are holding
1460 // here in mJournal.
1461 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001462 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001463 for (BackupRequest req : mQueue) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07001464 dataChangedImpl(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001465 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001466
1467 // We also want to reset the backup schedule based on whatever
1468 // the transport suggests by way of retry/backoff time.
1469 try {
1470 startBackupAlarmsLocked(mTransport.requestBackupTime());
1471 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001472 }
1473
1474 // Either backup was successful, in which case we of course do not need
1475 // this pass's journal any more; or it failed, in which case we just
1476 // re-enqueued all of these packages in the current active journal.
1477 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001478 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001480 }
1481
Christopher Tatec2af5d32010-02-02 15:18:58 -08001482 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001483 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001484 backupNow();
1485 }
1486
Dan Egnorbb9001c2009-07-27 12:20:13 -07001487 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001488 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001489 }
1490
Dan Egnor01445162009-09-21 17:04:05 -07001491 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001492 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001493 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001494
Christopher Tatec28083a2010-12-14 16:16:44 -08001495 // Verify that the requested app exists; it might be something that
1496 // requested a backup but was then uninstalled. The request was
1497 // journalled and rather than tamper with the journal it's safer
1498 // to sanity-check here.
1499 try {
1500 mPackageManager.getPackageInfo(request.appInfo.packageName, 0);
1501 } catch (NameNotFoundException e) {
1502 Slog.d(TAG, "Package does not exist; skipping");
1503 continue;
1504 }
1505
Christopher Tate043dadc2009-06-02 16:11:00 -07001506 IBackupAgent agent = null;
Christopher Tate043dadc2009-06-02 16:11:00 -07001507 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001508 mWakelock.setWorkSource(new WorkSource(request.appInfo.uid));
Christopher Tate4a627c72011-04-01 14:43:32 -07001509 agent = bindToAgentSynchronous(request.appInfo,
1510 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001511 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001512 int result = processOneBackup(request, agent, transport);
1513 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001514 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001515 } catch (SecurityException ex) {
1516 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001517 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001518 } finally {
1519 try { // unbind even on timeout, just in case
1520 mActivityManager.unbindBackupAgent(request.appInfo);
1521 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001522 }
1523 }
Dan Egnor01445162009-09-21 17:04:05 -07001524
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001525 mWakelock.setWorkSource(null);
1526
Dan Egnor01445162009-09-21 17:04:05 -07001527 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001528 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001529
Dan Egnor01445162009-09-21 17:04:05 -07001530 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1531 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001532 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001533 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001534
Dan Egnorbb9001c2009-07-27 12:20:13 -07001535 File savedStateName = new File(mStateDir, packageName);
1536 File backupDataName = new File(mDataDir, packageName + ".data");
1537 File newStateName = new File(mStateDir, packageName + ".new");
1538
1539 ParcelFileDescriptor savedState = null;
1540 ParcelFileDescriptor backupData = null;
1541 ParcelFileDescriptor newState = null;
1542
1543 PackageInfo packInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001544 final int token = generateToken();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001545 try {
1546 // Look up the package info & signatures. This is first so that if it
1547 // throws an exception, there's no file setup yet that would need to
1548 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001549 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1550 // The metadata 'package' is synthetic
1551 packInfo = new PackageInfo();
1552 packInfo.packageName = packageName;
1553 } else {
1554 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001555 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001556 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001557
Christopher Tatec7b31e32009-06-10 15:49:30 -07001558 // In a full backup, we pass a null ParcelFileDescriptor as
Christopher Tate4a627c72011-04-01 14:43:32 -07001559 // the saved-state "file". This is by definition an incremental,
1560 // so we build a saved state file to pass.
1561 savedState = ParcelFileDescriptor.open(savedStateName,
1562 ParcelFileDescriptor.MODE_READ_ONLY |
1563 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
Christopher Tatec7b31e32009-06-10 15:49:30 -07001564
Dan Egnorbb9001c2009-07-27 12:20:13 -07001565 backupData = ParcelFileDescriptor.open(backupDataName,
1566 ParcelFileDescriptor.MODE_READ_WRITE |
1567 ParcelFileDescriptor.MODE_CREATE |
1568 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001569
Dan Egnorbb9001c2009-07-27 12:20:13 -07001570 newState = ParcelFileDescriptor.open(newStateName,
1571 ParcelFileDescriptor.MODE_READ_WRITE |
1572 ParcelFileDescriptor.MODE_CREATE |
1573 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001574
Christopher Tate44a27902010-01-27 17:15:49 -08001575 // Initiate the target's backup pass
1576 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
Christopher Tate4a627c72011-04-01 14:43:32 -07001577 agent.doBackup(savedState, backupData, newState, false,
1578 token, mBackupManagerBinder);
Christopher Tate44a27902010-01-27 17:15:49 -08001579 boolean success = waitUntilOperationComplete(token);
1580
1581 if (!success) {
1582 // timeout -- bail out into the failed-transaction logic
1583 throw new RuntimeException("Backup timeout");
1584 }
1585
Dan Egnorbb9001c2009-07-27 12:20:13 -07001586 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001587 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001588 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001590 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001591 backupDataName.delete();
1592 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001593 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001594 } finally {
1595 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1596 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1597 try { if (newState != null) newState.close(); } catch (IOException e) {}
1598 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001599 synchronized (mCurrentOpLock) {
1600 mCurrentOperations.clear();
1601 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001602 }
1603
1604 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001605 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001606 try {
1607 int size = (int) backupDataName.length();
1608 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001609 if (result == BackupConstants.TRANSPORT_OK) {
1610 backupData = ParcelFileDescriptor.open(backupDataName,
1611 ParcelFileDescriptor.MODE_READ_ONLY);
1612 result = transport.performBackup(packInfo, backupData);
1613 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001614
Dan Egnor83861e72009-09-17 16:17:55 -07001615 // TODO - We call finishBackup() for each application backed up, because
1616 // we need to know now whether it succeeded or failed. Instead, we should
1617 // hold off on finishBackup() until the end, which implies holding off on
1618 // renaming *all* the output state files (see below) until that happens.
1619
Dan Egnor01445162009-09-21 17:04:05 -07001620 if (result == BackupConstants.TRANSPORT_OK) {
1621 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001622 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001623 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001624 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001625 }
1626
1627 // After successful transport, delete the now-stale data
1628 // and juggle the files so that next time we supply the agent
1629 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001630 if (result == BackupConstants.TRANSPORT_OK) {
1631 backupDataName.delete();
1632 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001633 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001634 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001635 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001636 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001637 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001638 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001639 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001640 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001641 } finally {
1642 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001643 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001644
Dan Egnor01445162009-09-21 17:04:05 -07001645 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001646 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001647 }
1648
Christopher Tatedf01dea2009-06-09 20:45:02 -07001649
Christopher Tate4a627c72011-04-01 14:43:32 -07001650 // ----- Full backup to a file/socket -----
1651
1652 class PerformFullBackupTask implements Runnable {
1653 ParcelFileDescriptor mOutputFile;
1654 IFullBackupRestoreObserver mObserver;
1655 boolean mIncludeApks;
1656 boolean mIncludeShared;
1657 boolean mAllApps;
1658 String[] mPackages;
1659 AtomicBoolean mLatchObject;
1660 File mFilesDir;
1661 File mManifestFile;
1662
1663 PerformFullBackupTask(ParcelFileDescriptor fd, IFullBackupRestoreObserver observer,
1664 boolean includeApks, boolean includeShared,
1665 boolean doAllApps, String[] packages, AtomicBoolean latch) {
1666 mOutputFile = fd;
1667 mObserver = observer;
1668 mIncludeApks = includeApks;
1669 mIncludeShared = includeShared;
1670 mAllApps = doAllApps;
1671 mPackages = packages;
1672 mLatchObject = latch;
1673
1674 mFilesDir = new File("/data/system");
1675 mManifestFile = new File(mFilesDir, BACKUP_MANIFEST_FILENAME);
1676 }
1677
1678 @Override
1679 public void run() {
1680 final List<PackageInfo> packagesToBackup;
1681
1682 sendStartBackup();
1683
1684 // doAllApps supersedes the package set if any
1685 if (mAllApps) {
1686 packagesToBackup = mPackageManager.getInstalledPackages(
1687 PackageManager.GET_SIGNATURES);
1688 } else {
1689 packagesToBackup = new ArrayList<PackageInfo>();
1690 for (String pkgName : mPackages) {
1691 try {
1692 packagesToBackup.add(mPackageManager.getPackageInfo(pkgName,
1693 PackageManager.GET_SIGNATURES));
1694 } catch (NameNotFoundException e) {
1695 Slog.w(TAG, "Unknown package " + pkgName + ", skipping");
1696 }
1697 }
1698 }
1699
1700 // Now back up the app data via the agent mechanism
1701 PackageInfo pkg = null;
1702 try {
1703 int N = packagesToBackup.size();
1704 for (int i = 0; i < N; i++) {
1705 pkg = packagesToBackup.get(i);
1706
1707 Slog.d(TAG, "Binding to full backup agent : " + pkg.packageName);
1708
1709 IBackupAgent agent = bindToAgentSynchronous(pkg.applicationInfo,
1710 IApplicationThread.BACKUP_MODE_FULL);
1711 if (agent != null) {
1712 try {
Christopher Tatedc92c822011-05-13 15:38:02 -07001713 ApplicationInfo app = pkg.applicationInfo;
Christopher Tate4a627c72011-04-01 14:43:32 -07001714 boolean sendApk = mIncludeApks
1715 && ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) == 0)
1716 && ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
1717 (app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
1718
1719 sendOnBackupPackage(pkg.packageName);
1720
1721 {
1722 BackupDataOutput output = new BackupDataOutput(
1723 mOutputFile.getFileDescriptor());
1724
1725 if (DEBUG) Slog.d(TAG, "Writing manifest for " + pkg.packageName);
1726 writeAppManifest(pkg, mManifestFile, sendApk);
1727 FullBackup.backupToTar(pkg.packageName, null, null,
1728 mFilesDir.getAbsolutePath(),
1729 mManifestFile.getAbsolutePath(),
1730 output);
1731 }
1732
1733 if (DEBUG) Slog.d(TAG, "Calling doBackup()");
1734 final int token = generateToken();
1735 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL);
1736 agent.doBackup(null, mOutputFile, null, sendApk,
1737 token, mBackupManagerBinder);
1738 boolean success = waitUntilOperationComplete(token);
1739 if (!success) {
1740 Slog.d(TAG, "Full backup failed on package " + pkg.packageName);
1741 } else {
1742 if (DEBUG) Slog.d(TAG, "Full backup success: " + pkg.packageName);
1743 }
Christopher Tate4a627c72011-04-01 14:43:32 -07001744 } catch (IOException e) {
1745 Slog.e(TAG, "Error backing up " + pkg.packageName, e);
1746 }
1747 } else {
1748 Slog.w(TAG, "Unable to bind to full agent for " + pkg.packageName);
1749 }
1750 tearDown(pkg);
1751 }
1752 } catch (RemoteException e) {
1753 Slog.e(TAG, "App died during full backup");
1754 } finally {
1755 if (pkg != null) {
1756 tearDown(pkg);
1757 }
1758 try {
1759 mOutputFile.close();
1760 } catch (IOException e) {
1761 /* nothing we can do about this */
1762 }
1763 synchronized (mCurrentOpLock) {
1764 mCurrentOperations.clear();
1765 }
1766 synchronized (mLatchObject) {
1767 mLatchObject.set(true);
1768 mLatchObject.notifyAll();
1769 }
1770 sendEndBackup();
1771 mWakelock.release();
1772 if (DEBUG) Slog.d(TAG, "Full backup pass complete.");
1773 }
1774 }
1775
1776 private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
1777 throws IOException {
1778 // Manifest format. All data are strings ending in LF:
1779 // BACKUP_MANIFEST_VERSION, currently 1
1780 //
1781 // Version 1:
1782 // package name
1783 // package's versionCode
1784 // boolean: "1" if archive includes .apk, "0" otherwise
1785 // number of signatures == N
1786 // N*: signature byte array in ascii format per Signature.toCharsString()
1787 StringBuilder builder = new StringBuilder(4096);
1788 StringBuilderPrinter printer = new StringBuilderPrinter(builder);
1789
1790 printer.println(Integer.toString(BACKUP_MANIFEST_VERSION));
1791 printer.println(pkg.packageName);
1792 printer.println(Integer.toString(pkg.versionCode));
1793 printer.println(withApk ? "1" : "0");
1794 if (pkg.signatures == null) {
1795 printer.println("0");
1796 } else {
1797 printer.println(Integer.toString(pkg.signatures.length));
1798 for (Signature sig : pkg.signatures) {
1799 printer.println(sig.toCharsString());
1800 }
1801 }
1802
1803 FileOutputStream outstream = new FileOutputStream(manifestFile);
1804 Libcore.os.ftruncate(outstream.getFD(), 0);
1805 outstream.write(builder.toString().getBytes());
1806 outstream.close();
1807 }
1808
1809 private void tearDown(PackageInfo pkg) {
1810 final ApplicationInfo app = pkg.applicationInfo;
1811 try {
1812 // unbind and tidy up even on timeout or failure, just in case
1813 mActivityManager.unbindBackupAgent(app);
1814
Christopher Tatedc92c822011-05-13 15:38:02 -07001815 // The agent was running with a stub Application object, so shut it down.
1816 // !!! We hardcode the confirmation UI's package name here rather than use a
1817 // manifest flag! TODO something less direct.
1818 if (app.uid != Process.SYSTEM_UID
1819 && !pkg.packageName.equals("com.android.backupconfirm")) {
Christopher Tate4a627c72011-04-01 14:43:32 -07001820 if (DEBUG) Slog.d(TAG, "Backup complete, killing host process");
1821 mActivityManager.killApplicationProcess(app.processName, app.uid);
1822 } else {
1823 if (DEBUG) Slog.d(TAG, "Not killing after restore: " + app.processName);
1824 }
1825 } catch (RemoteException e) {
1826 Slog.d(TAG, "Lost app trying to shut down");
1827 }
1828 }
1829
1830 // wrappers for observer use
1831 void sendStartBackup() {
1832 if (mObserver != null) {
1833 try {
1834 mObserver.onStartBackup();
1835 } catch (RemoteException e) {
1836 Slog.w(TAG, "full backup observer went away: startBackup");
1837 mObserver = null;
1838 }
1839 }
1840 }
1841
1842 void sendOnBackupPackage(String name) {
1843 if (mObserver != null) {
1844 try {
1845 // TODO: use a more user-friendly name string
1846 mObserver.onBackupPackage(name);
1847 } catch (RemoteException e) {
1848 Slog.w(TAG, "full backup observer went away: backupPackage");
1849 mObserver = null;
1850 }
1851 }
1852 }
1853
1854 void sendEndBackup() {
1855 if (mObserver != null) {
1856 try {
1857 mObserver.onEndBackup();
1858 } catch (RemoteException e) {
1859 Slog.w(TAG, "full backup observer went away: endBackup");
1860 mObserver = null;
1861 }
1862 }
1863 }
1864 }
1865
1866
Christopher Tatedf01dea2009-06-09 20:45:02 -07001867 // ----- Restore handling -----
1868
Christopher Tate78dd4a72009-11-04 11:49:08 -08001869 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1870 // If the target resides on the system partition, we allow it to restore
1871 // data from the like-named package in a restore set even if the signatures
1872 // do not match. (Unlike general applications, those flashed to the system
1873 // partition will be signed with the device's platform certificate, so on
1874 // different phones the same system app will have different signatures.)
1875 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001876 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001877 return true;
1878 }
1879
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001880 // Allow unsigned apps, but not signed on one device and unsigned on the other
1881 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001882 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001883 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001884 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001885 if ((storedSigs == null || storedSigs.length == 0)
1886 && (deviceSigs == null || deviceSigs.length == 0)) {
1887 return true;
1888 }
1889 if (storedSigs == null || deviceSigs == null) {
1890 return false;
1891 }
1892
Christopher Tateabce4e82009-06-18 18:35:32 -07001893 // !!! TODO: this demands that every stored signature match one
1894 // that is present on device, and does not demand the converse.
1895 // Is this this right policy?
1896 int nStored = storedSigs.length;
1897 int nDevice = deviceSigs.length;
1898
1899 for (int i=0; i < nStored; i++) {
1900 boolean match = false;
1901 for (int j=0; j < nDevice; j++) {
1902 if (storedSigs[i].equals(deviceSigs[j])) {
1903 match = true;
1904 break;
1905 }
1906 }
1907 if (!match) {
1908 return false;
1909 }
1910 }
1911 return true;
1912 }
1913
Christopher Tate44a27902010-01-27 17:15:49 -08001914 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001915 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001916 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001917 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001918 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001919 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001920 private int mPmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001921 private boolean mNeedFullBackup;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001922
Christopher Tate5cbbf562009-06-22 16:44:51 -07001923 class RestoreRequest {
1924 public PackageInfo app;
1925 public int storedAppVersion;
1926
1927 RestoreRequest(PackageInfo _app, int _version) {
1928 app = _app;
1929 storedAppVersion = _version;
1930 }
1931 }
1932
Christopher Tate44a27902010-01-27 17:15:49 -08001933 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Chris Tate249345b2010-10-29 12:57:04 -07001934 long restoreSetToken, PackageInfo targetPackage, int pmToken,
1935 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001936 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001937 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001938 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001939 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001940 mPmToken = pmToken;
Chris Tate249345b2010-10-29 12:57:04 -07001941 mNeedFullBackup = needFullBackup;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001942
1943 try {
1944 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1945 } catch (RemoteException e) {
1946 // can't happen; the transport is local
1947 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001948 }
1949
Christopher Tatedf01dea2009-06-09 20:45:02 -07001950 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001951 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001952 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001953 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001954 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001955
Christopher Tateb49ceb32010-02-08 16:22:24 -08001956 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001957 int error = -1; // assume error
1958
Dan Egnorefe52642009-06-24 00:16:33 -07001959 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001960 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001961 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001962 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001963
Dan Egnorefe52642009-06-24 00:16:33 -07001964 // Get the list of all packages which have backup enabled.
1965 // (Include the Package Manager metadata pseudo-package first.)
1966 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1967 PackageInfo omPackage = new PackageInfo();
1968 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1969 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001970
Dan Egnorefe52642009-06-24 00:16:33 -07001971 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001972 if (mTargetPackage == null) {
1973 restorePackages.addAll(agentPackages);
1974 } else {
1975 // Just one package to attempt restore of
1976 restorePackages.add(mTargetPackage);
1977 }
Dan Egnorefe52642009-06-24 00:16:33 -07001978
Christopher Tate7d562ec2009-06-25 18:03:43 -07001979 // let the observer know that we're running
1980 if (mObserver != null) {
1981 try {
1982 // !!! TODO: get an actual count from the transport after
1983 // its startRestore() runs?
1984 mObserver.restoreStarting(restorePackages.size());
1985 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001986 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001987 mObserver = null;
1988 }
1989 }
1990
Dan Egnor01445162009-09-21 17:04:05 -07001991 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1992 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001993 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001994 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001995 return;
1996 }
1997
1998 String packageName = mTransport.nextRestorePackage();
1999 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002000 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002001 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07002002 return;
2003 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002004 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002005 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002006 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07002007 return;
2008 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002009 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07002010 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002011 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002012 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002013 return;
2014 }
2015
2016 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08002017 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07002018 mPackageManager, agentPackages);
Chris Tate249345b2010-10-29 12:57:04 -07002019 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()),
2020 mNeedFullBackup);
Dan Egnorefe52642009-06-24 00:16:33 -07002021
Christopher Tate8c032472009-07-02 14:28:47 -07002022 // Verify that the backup set includes metadata. If not, we can't do
2023 // signature/version verification etc, so we simply do not proceed with
2024 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07002025 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002026 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002027 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002028 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07002029 return;
2030 }
2031
Christopher Tate7d562ec2009-06-25 18:03:43 -07002032 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07002033 for (;;) {
2034 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002035
Dan Egnorefe52642009-06-24 00:16:33 -07002036 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002037 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002038 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07002039 return;
2040 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002041 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07002042 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07002043 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002044
Christopher Tate7d562ec2009-06-25 18:03:43 -07002045 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07002046 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07002047 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07002048 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002049 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07002050 mObserver = null;
2051 }
2052 }
2053
Dan Egnorefe52642009-06-24 00:16:33 -07002054 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
2055 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002056 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002057 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002058 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002059 continue;
2060 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002061
Dan Egnorbb9001c2009-07-27 12:20:13 -07002062 PackageInfo packageInfo;
2063 try {
2064 int flags = PackageManager.GET_SIGNATURES;
2065 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
2066 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002067 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002068 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002069 "Package missing on device");
2070 continue;
2071 }
2072
Dan Egnorefe52642009-06-24 00:16:33 -07002073 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08002074 // Data is from a "newer" version of the app than we have currently
2075 // installed. If the app has not declared that it is prepared to
2076 // handle this case, we do not attempt the restore.
2077 if ((packageInfo.applicationInfo.flags
2078 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
2079 String message = "Version " + metaInfo.versionCode
2080 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002081 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08002082 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
2083 packageName, message);
2084 continue;
2085 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002086 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08002087 + " > installed " + packageInfo.versionCode
2088 + " but restoreAnyVersion");
2089 }
Dan Egnorefe52642009-06-24 00:16:33 -07002090 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002091
Christopher Tate78dd4a72009-11-04 11:49:08 -08002092 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002093 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002094 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002095 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07002096 continue;
2097 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002098
Joe Onorato8a9b2202010-02-26 18:56:32 -08002099 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07002100 + " restore version [" + metaInfo.versionCode
2101 + "] is compatible with installed version ["
2102 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07002103
Christopher Tate3de55bc2010-03-12 17:28:08 -08002104 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07002105 IBackupAgent agent = bindToAgentSynchronous(
2106 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08002107 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07002108 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002109 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002110 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07002111 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07002112 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07002113 }
2114
Christopher Tate5e1ab332009-09-01 20:32:49 -07002115 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07002116 try {
Chris Tate249345b2010-10-29 12:57:04 -07002117 processOneRestore(packageInfo, metaInfo.versionCode, agent,
2118 mNeedFullBackup);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002119 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07002120 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07002121 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07002122 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07002123
2124 // The agent was probably running with a stub Application object,
2125 // which isn't a valid run mode for the main app logic. Shut
2126 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08002127 // usual full initialization. Note that this is only done for
2128 // full-system restores: when a single app has requested a restore,
2129 // it is explicitly not killed following that operation.
2130 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07002131 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002132 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07002133 + packageInfo.applicationInfo.processName);
2134 mActivityManager.killApplicationProcess(
2135 packageInfo.applicationInfo.processName,
2136 packageInfo.applicationInfo.uid);
2137 }
Dan Egnorefe52642009-06-24 00:16:33 -07002138 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002139 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07002140
2141 // if we get this far, report success to the observer
2142 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07002143 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002144 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002145 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002146 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07002147 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002148 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002149
Dan Egnorefe52642009-06-24 00:16:33 -07002150 try {
2151 mTransport.finishRestore();
2152 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002153 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07002154 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07002155
2156 if (mObserver != null) {
2157 try {
2158 mObserver.restoreFinished(error);
2159 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002160 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07002161 }
2162 }
Christopher Tateb6787f22009-07-02 17:40:45 -07002163
Christopher Tate84725812010-02-04 15:52:40 -08002164 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08002165 // ancestral dataset, as well as the set of apps that are possibly
2166 // restoreable from the dataset
2167 if (mTargetPackage == null && pmAgent != null) {
2168 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08002169 mAncestralToken = mToken;
2170 writeRestoreTokens();
2171 }
2172
Christopher Tate1bb69062010-02-19 17:02:12 -08002173 // We must under all circumstances tell the Package Manager to
2174 // proceed with install notifications if it's waiting for us.
2175 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002176 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08002177 try {
2178 mPackageManagerBinder.finishPackageInstall(mPmToken);
2179 } catch (RemoteException e) { /* can't happen */ }
2180 }
2181
Christopher Tate73a3cb32010-12-13 18:27:26 -08002182 // Furthermore we need to reset the session timeout clock
2183 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
2184 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT,
2185 TIMEOUT_RESTORE_INTERVAL);
2186
Christopher Tateb6787f22009-07-02 17:40:45 -07002187 // done; we can finally release the wakelock
2188 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07002189 }
2190 }
2191
Dan Egnorefe52642009-06-24 00:16:33 -07002192 // Do the guts of a restore of one application, using mTransport.getRestoreData().
Chris Tate249345b2010-10-29 12:57:04 -07002193 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent,
2194 boolean needFullBackup) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07002195 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07002196 final String packageName = app.packageName;
2197
Joe Onorato8a9b2202010-02-26 18:56:32 -08002198 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002199
Christopher Tatec7b31e32009-06-10 15:49:30 -07002200 // !!! TODO: get the dirs from the transport
2201 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07002202 File newStateName = new File(mStateDir, packageName + ".new");
2203 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002204
Dan Egnorbb9001c2009-07-27 12:20:13 -07002205 ParcelFileDescriptor backupData = null;
2206 ParcelFileDescriptor newState = null;
2207
Christopher Tate4a627c72011-04-01 14:43:32 -07002208 final int token = generateToken();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002209 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07002210 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07002211 backupData = ParcelFileDescriptor.open(backupDataName,
2212 ParcelFileDescriptor.MODE_READ_WRITE |
2213 ParcelFileDescriptor.MODE_CREATE |
2214 ParcelFileDescriptor.MODE_TRUNCATE);
2215
Dan Egnor01445162009-09-21 17:04:05 -07002216 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002217 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002218 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07002219 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07002220 }
2221
2222 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07002223 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07002224 backupData = ParcelFileDescriptor.open(backupDataName,
2225 ParcelFileDescriptor.MODE_READ_ONLY);
2226
Dan Egnorbb9001c2009-07-27 12:20:13 -07002227 newState = ParcelFileDescriptor.open(newStateName,
2228 ParcelFileDescriptor.MODE_READ_WRITE |
2229 ParcelFileDescriptor.MODE_CREATE |
2230 ParcelFileDescriptor.MODE_TRUNCATE);
2231
Christopher Tate44a27902010-01-27 17:15:49 -08002232 // Kick off the restore, checking for hung agents
2233 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
2234 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
2235 boolean success = waitUntilOperationComplete(token);
2236
2237 if (!success) {
2238 throw new RuntimeException("restore timeout");
2239 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002240
2241 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07002242 //
2243 // !!! TODO: the restored data should be migrated on the server
2244 // side into the current dataset. In that case the new state file
2245 // we just created would reflect the data already extant in the
2246 // backend, so there'd be nothing more to do. Until that happens,
2247 // however, we need to make sure that we record the data to the
2248 // current backend dataset. (Yes, this means shipping the data over
2249 // the wire in both directions. That's bad, but consistency comes
2250 // first, then efficiency.) Once we introduce server-side data
2251 // migration to the newly-restored device's dataset, we will change
2252 // the following from a discard of the newly-written state to the
2253 // "correct" operation of renaming into the canonical state blob.
2254 newStateName.delete(); // TODO: remove; see above comment
2255 //newStateName.renameTo(savedStateName); // TODO: replace with this
2256
Dan Egnorbb9001c2009-07-27 12:20:13 -07002257 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002258 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07002259 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002260 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002261 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07002262
Christopher Tate96733042009-07-20 14:49:13 -07002263 // If the agent fails restore, it might have put the app's data
2264 // into an incoherent state. For consistency we wipe its data
2265 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07002266 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07002267 } finally {
2268 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07002269 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
2270 try { if (newState != null) newState.close(); } catch (IOException e) {}
2271 backupData = newState = null;
Christopher Tate4a627c72011-04-01 14:43:32 -07002272 synchronized (mCurrentOperations) {
2273 mCurrentOperations.delete(token);
2274 }
Chris Tate249345b2010-10-29 12:57:04 -07002275
2276 // If we know a priori that we'll need to perform a full post-restore backup
2277 // pass, clear the new state file data. This means we're discarding work that
2278 // was just done by the app's agent, but this way the agent doesn't need to
2279 // take any special action based on global device state.
2280 if (needFullBackup) {
2281 newStateName.delete();
2282 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07002283 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002284 }
2285 }
2286
Christopher Tate44a27902010-01-27 17:15:49 -08002287 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07002288 IBackupTransport mTransport;
2289 PackageInfo mPackage;
2290
Christopher Tate44a27902010-01-27 17:15:49 -08002291 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07002292 mTransport = transport;
2293 mPackage = packageInfo;
2294 }
2295
Christopher Tateee0e78a2009-07-02 11:17:03 -07002296 public void run() {
2297 try {
2298 // Clear the on-device backup state to ensure a full backup next time
2299 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
2300 File stateFile = new File(stateDir, mPackage.packageName);
2301 stateFile.delete();
2302
2303 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07002304 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07002305 mTransport.clearBackupData(mPackage);
2306 } catch (RemoteException e) {
2307 // can't happen; the transport is local
2308 } finally {
2309 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07002310 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07002311 mTransport.finishBackup();
2312 } catch (RemoteException e) {
2313 // can't happen; the transport is local
2314 }
Christopher Tateb6787f22009-07-02 17:40:45 -07002315
2316 // Last but not least, release the cpu
2317 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002318 }
2319 }
2320 }
2321
Christopher Tate44a27902010-01-27 17:15:49 -08002322 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002323 HashSet<String> mQueue;
2324
Christopher Tate44a27902010-01-27 17:15:49 -08002325 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002326 mQueue = transportNames;
2327 }
2328
Christopher Tate4cc86e12009-09-21 19:36:51 -07002329 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07002330 try {
2331 for (String transportName : mQueue) {
2332 IBackupTransport transport = getTransport(transportName);
2333 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002334 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002335 continue;
2336 }
2337
Joe Onorato8a9b2202010-02-26 18:56:32 -08002338 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002339 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07002340 long startRealtime = SystemClock.elapsedRealtime();
2341 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07002342
Christopher Tate4cc86e12009-09-21 19:36:51 -07002343 if (status == BackupConstants.TRANSPORT_OK) {
2344 status = transport.finishBackup();
2345 }
2346
2347 // Okay, the wipe really happened. Clean up our local bookkeeping.
2348 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002349 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07002350 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002351 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07002352 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002353 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002354 synchronized (mQueueLock) {
2355 recordInitPendingLocked(false, transportName);
2356 }
Dan Egnor726247c2009-09-29 19:12:31 -07002357 } else {
2358 // If this didn't work, requeue this one and try again
2359 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08002360 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002361 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002362 synchronized (mQueueLock) {
2363 recordInitPendingLocked(true, transportName);
2364 }
2365 // do this via another alarm to make sure of the wakelock states
2366 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002367 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07002368 + transportName + " resched in " + delay);
2369 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
2370 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002371 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07002372 }
2373 } catch (RemoteException e) {
2374 // can't happen; the transports are local
2375 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002376 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002377 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08002378 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07002379 mWakelock.release();
2380 }
2381 }
2382 }
2383
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002384 private void dataChangedImpl(String packageName) {
2385 HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2386 dataChangedImpl(packageName, targets);
2387 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002388
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002389 private void dataChangedImpl(String packageName, HashSet<ApplicationInfo> targets) {
Christopher Tate487529a2009-04-29 14:03:25 -07002390 // Record that we need a backup pass for the caller. Since multiple callers
2391 // may share a uid, we need to note all candidates within that uid and schedule
2392 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002393 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002394
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002395 if (targets == null) {
2396 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2397 + " uid=" + Binder.getCallingUid());
2398 return;
2399 }
2400
2401 synchronized (mQueueLock) {
2402 // Note that this client has made data changes that need to be backed up
2403 for (ApplicationInfo app : targets) {
2404 // validate the caller-supplied package name against the known set of
2405 // packages associated with this uid
2406 if (app.packageName.equals(packageName)) {
2407 // Add the caller to the set of pending backups. If there is
2408 // one already there, then overwrite it, but no harm done.
Christopher Tate4a627c72011-04-01 14:43:32 -07002409 BackupRequest req = new BackupRequest(app);
Christopher Tatec28083a2010-12-14 16:16:44 -08002410 if (mPendingBackups.put(app.packageName, req) == null) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002411 // Journal this request in case of crash. The put()
2412 // operation returned null when this package was not already
2413 // in the set; we want to avoid touching the disk redundantly.
2414 writeToJournalLocked(packageName);
2415
2416 if (DEBUG) {
2417 int numKeys = mPendingBackups.size();
2418 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
2419 for (BackupRequest b : mPendingBackups.values()) {
2420 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
2421 }
2422 }
2423 }
2424 }
2425 }
2426 }
2427 }
2428
2429 // Note: packageName is currently unused, but may be in the future
2430 private HashSet<ApplicationInfo> dataChangedTargets(String packageName) {
Christopher Tate63d27002009-06-16 17:16:42 -07002431 // If the caller does not hold the BACKUP permission, it can only request a
2432 // backup of its own data.
Dianne Hackborncf098292009-07-01 19:55:20 -07002433 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002434 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002435 synchronized (mBackupParticipants) {
2436 return mBackupParticipants.get(Binder.getCallingUid());
2437 }
2438 }
2439
2440 // a caller with full permission can ask to back up any participating app
2441 // !!! TODO: allow backup of ANY app?
2442 HashSet<ApplicationInfo> targets = new HashSet<ApplicationInfo>();
2443 synchronized (mBackupParticipants) {
Christopher Tate63d27002009-06-16 17:16:42 -07002444 int N = mBackupParticipants.size();
2445 for (int i = 0; i < N; i++) {
2446 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2447 if (s != null) {
2448 targets.addAll(s);
2449 }
2450 }
2451 }
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002452 return targets;
Christopher Tate487529a2009-04-29 14:03:25 -07002453 }
Christopher Tate46758122009-05-06 11:22:00 -07002454
Christopher Tatecde87f42009-06-12 12:55:53 -07002455 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002456 RandomAccessFile out = null;
2457 try {
2458 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2459 out = new RandomAccessFile(mJournal, "rws");
2460 out.seek(out.length());
2461 out.writeUTF(str);
2462 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002463 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002464 mJournal = null;
2465 } finally {
2466 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002467 }
2468 }
2469
Brad Fitzpatrick3dd42332010-09-07 23:40:30 -07002470 // ----- IBackupManager binder interface -----
2471
2472 public void dataChanged(final String packageName) {
2473 final HashSet<ApplicationInfo> targets = dataChangedTargets(packageName);
2474 if (targets == null) {
2475 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
2476 + " uid=" + Binder.getCallingUid());
2477 return;
2478 }
2479
2480 mBackupHandler.post(new Runnable() {
2481 public void run() {
2482 dataChangedImpl(packageName, targets);
2483 }
2484 });
2485 }
2486
Christopher Tateee0e78a2009-07-02 11:17:03 -07002487 // Clear the given package's backup data from the current transport
2488 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002489 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002490 PackageInfo info;
2491 try {
2492 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2493 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002494 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002495 return;
2496 }
2497
2498 // If the caller does not hold the BACKUP permission, it can only request a
2499 // wipe of its own backed-up data.
2500 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002501 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002502 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2503 apps = mBackupParticipants.get(Binder.getCallingUid());
2504 } else {
2505 // a caller with full permission can ask to back up any participating app
2506 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002507 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002508 apps = new HashSet<ApplicationInfo>();
2509 int N = mBackupParticipants.size();
2510 for (int i = 0; i < N; i++) {
2511 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2512 if (s != null) {
2513 apps.addAll(s);
2514 }
2515 }
2516 }
2517
2518 // now find the given package in the set of candidate apps
2519 for (ApplicationInfo app : apps) {
2520 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002521 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002522 // found it; fire off the clear request
2523 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002524 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002525 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002526 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2527 new ClearParams(getTransport(mCurrentTransport), info));
2528 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002529 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002530 }
2531 break;
2532 }
2533 }
2534 }
2535
Christopher Tateace7f092009-06-15 18:07:25 -07002536 // Run a backup pass immediately for any applications that have declared
2537 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002538 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002539 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002540
Joe Onorato8a9b2202010-02-26 18:56:32 -08002541 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002542 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002543 // Because the alarms we are using can jitter, and we want an *immediate*
2544 // backup pass to happen, we restart the timer beginning with "next time,"
2545 // then manually fire the backup trigger intent ourselves.
2546 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002547 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002548 mRunBackupIntent.send();
2549 } catch (PendingIntent.CanceledException e) {
2550 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002551 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002552 }
Christopher Tate46758122009-05-06 11:22:00 -07002553 }
2554 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002555
Christopher Tate4a627c72011-04-01 14:43:32 -07002556 // Run a *full* backup pass for the given package, writing the resulting data stream
2557 // to the supplied file descriptor. This method is synchronous and does not return
2558 // to the caller until the backup has been completed.
2559 public void fullBackup(ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
2560 boolean doAllApps, String[] pkgList) {
2561 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
2562
2563 // Validate
2564 if (!doAllApps) {
2565 if (!includeShared) {
2566 // If we're backing up shared data (sdcard or equivalent), then we can run
2567 // without any supplied app names. Otherwise, we'd be doing no work, so
2568 // report the error.
2569 if (pkgList == null || pkgList.length == 0) {
2570 throw new IllegalArgumentException(
2571 "Backup requested but neither shared nor any apps named");
2572 }
2573 }
2574 }
2575
2576 if (DEBUG) Slog.v(TAG, "Requesting full backup: apks=" + includeApks
2577 + " shared=" + includeShared + " all=" + doAllApps
2578 + " pkgs=" + pkgList);
2579
2580 long oldId = Binder.clearCallingIdentity();
2581 try {
2582 FullBackupParams params = new FullBackupParams(fd, includeApks, includeShared,
2583 doAllApps, pkgList);
2584 final int token = generateToken();
2585 synchronized (mFullConfirmations) {
2586 mFullConfirmations.put(token, params);
2587 }
2588
2589 // start up the confirmation UI, making sure the screen lights up
2590 if (DEBUG) Slog.d(TAG, "Starting confirmation UI, token=" + token);
2591 try {
2592 Intent confIntent = new Intent(FullBackup.FULL_BACKUP_INTENT_ACTION);
2593 confIntent.setClassName("com.android.backupconfirm",
2594 "com.android.backupconfirm.BackupRestoreConfirmation");
2595 confIntent.putExtra(FullBackup.CONF_TOKEN_INTENT_EXTRA, token);
2596 confIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2597 mContext.startActivity(confIntent);
2598 } catch (ActivityNotFoundException e) {
2599 Slog.e(TAG, "Unable to launch full backup confirmation", e);
2600 mFullConfirmations.delete(token);
2601 return;
2602 }
2603 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
2604
2605 // start the confirmation countdown
2606 if (DEBUG) Slog.d(TAG, "Posting conf timeout msg after "
2607 + TIMEOUT_FULL_CONFIRMATION + " millis");
2608 Message msg = mBackupHandler.obtainMessage(MSG_FULL_CONFIRMATION_TIMEOUT,
2609 token, 0, params);
2610 mBackupHandler.sendMessageDelayed(msg, TIMEOUT_FULL_CONFIRMATION);
2611
2612 // wait for the backup to be performed
2613 if (DEBUG) Slog.d(TAG, "Waiting for full backup completion...");
2614 waitForCompletion(params);
2615 if (DEBUG) Slog.d(TAG, "...Full backup operation complete!");
2616 } finally {
2617 Binder.restoreCallingIdentity(oldId);
2618 try {
2619 fd.close();
2620 } catch (IOException e) {
2621 // just eat it
2622 }
2623 }
2624 }
2625
2626 void waitForCompletion(FullParams params) {
2627 synchronized (params.latch) {
2628 while (params.latch.get() == false) {
2629 try {
2630 params.latch.wait();
2631 } catch (InterruptedException e) { /* never interrupted */ }
2632 }
2633 }
2634 }
2635
2636 void signalFullBackupRestoreCompletion(FullParams params) {
2637 synchronized (params.latch) {
2638 params.latch.set(true);
2639 params.latch.notifyAll();
2640 }
2641 }
2642
2643 // Confirm that the previously-requested full backup/restore operation can proceed. This
2644 // is used to require a user-facing disclosure about the operation.
2645 public void acknowledgeFullBackupOrRestore(int token, boolean allow,
2646 IFullBackupRestoreObserver observer) {
2647 if (DEBUG) Slog.d(TAG, "acknowledgeFullBackupOrRestore : token=" + token
2648 + " allow=" + allow);
2649
2650 // TODO: possibly require not just this signature-only permission, but even
2651 // require that the specific designated confirmation-UI app uid is the caller?
2652 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "fullBackup");
2653
2654 long oldId = Binder.clearCallingIdentity();
2655 try {
2656
2657 FullParams params;
2658 synchronized (mFullConfirmations) {
2659 params = mFullConfirmations.get(token);
2660 if (params != null) {
2661 mBackupHandler.removeMessages(MSG_FULL_CONFIRMATION_TIMEOUT, params);
2662 mFullConfirmations.delete(token);
2663
2664 if (allow) {
2665 params.observer = observer;
2666 final int verb = params instanceof FullBackupParams
2667 ? MSG_RUN_FULL_BACKUP
2668 : MSG_RUN_FULL_RESTORE;
2669
2670 mWakelock.acquire();
2671 Message msg = mBackupHandler.obtainMessage(verb, params);
2672 mBackupHandler.sendMessage(msg);
2673 } else {
2674 Slog.w(TAG, "User rejected full backup/restore operation");
2675 // indicate completion without having actually transferred any data
2676 signalFullBackupRestoreCompletion(params);
2677 }
2678 } else {
2679 Slog.w(TAG, "Attempted to ack full backup/restore with invalid token");
2680 }
2681 }
2682 } finally {
2683 Binder.restoreCallingIdentity(oldId);
2684 }
2685 }
2686
Christopher Tate8031a3d2009-07-06 16:36:05 -07002687 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002688 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002689 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4a627c72011-04-01 14:43:32 -07002690 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002691
Joe Onorato8a9b2202010-02-26 18:56:32 -08002692 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002693
Christopher Tate6ef58a12009-06-29 14:56:28 -07002694 boolean wasEnabled = mEnabled;
2695 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002696 Settings.Secure.putInt(mContext.getContentResolver(),
2697 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002698 mEnabled = enable;
2699 }
2700
Christopher Tate49401dd2009-07-01 12:34:29 -07002701 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002702 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002703 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002704 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002705 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002706 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002707 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002708
Christopher Tateb6787f22009-07-02 17:40:45 -07002709 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002710
2711 // This also constitutes an opt-out, so we wipe any data for
2712 // this device from the backend. We start that process with
2713 // an alarm in order to guarantee wakelock states.
2714 if (wasEnabled && mProvisioned) {
2715 // NOTE: we currently flush every registered transport, not just
2716 // the currently-active one.
2717 HashSet<String> allTransports;
2718 synchronized (mTransports) {
2719 allTransports = new HashSet<String>(mTransports.keySet());
2720 }
2721 // build the set of transports for which we are posting an init
2722 for (String transport : allTransports) {
2723 recordInitPendingLocked(true, transport);
2724 }
2725 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2726 mRunInitIntent);
2727 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002728 }
2729 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002730 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002731
Christopher Tatecce9da52010-02-03 15:11:15 -08002732 // Enable/disable automatic restore of app data at install time
2733 public void setAutoRestore(boolean doAutoRestore) {
2734 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2735 "setBackupEnabled");
2736
Joe Onorato8a9b2202010-02-26 18:56:32 -08002737 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002738
2739 synchronized (this) {
2740 Settings.Secure.putInt(mContext.getContentResolver(),
2741 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2742 mAutoRestore = doAutoRestore;
2743 }
2744 }
2745
Christopher Tate8031a3d2009-07-06 16:36:05 -07002746 // Mark the backup service as having been provisioned
2747 public void setBackupProvisioned(boolean available) {
2748 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2749 "setBackupProvisioned");
2750
2751 boolean wasProvisioned = mProvisioned;
2752 synchronized (this) {
2753 Settings.Secure.putInt(mContext.getContentResolver(),
2754 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2755 mProvisioned = available;
2756 }
2757
2758 synchronized (mQueueLock) {
2759 if (available && !wasProvisioned && mEnabled) {
2760 // we're now good to go, so start the backup alarms
2761 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2762 } else if (!available) {
2763 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002764 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002765 mAlarmManager.cancel(mRunBackupIntent);
2766 }
2767 }
2768 }
2769
2770 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002771 // We used to use setInexactRepeating(), but that may be linked to
2772 // backups running at :00 more often than not, creating load spikes.
2773 // Schedule at an exact time for now, and also add a bit of "fuzz".
2774
2775 Random random = new Random();
2776 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2777 random.nextInt(FUZZ_MILLIS);
2778 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2779 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002780 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002781 }
2782
Christopher Tate6ef58a12009-06-29 14:56:28 -07002783 // Report whether the backup mechanism is currently enabled
2784 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002785 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002786 return mEnabled; // no need to synchronize just to read it
2787 }
2788
Christopher Tate91717492009-06-26 21:07:13 -07002789 // Report the name of the currently active transport
2790 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002791 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002792 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002793 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002794 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002795 }
2796
Christopher Tate91717492009-06-26 21:07:13 -07002797 // Report all known, available backup transports
2798 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002799 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002800
Christopher Tate91717492009-06-26 21:07:13 -07002801 String[] list = null;
2802 ArrayList<String> known = new ArrayList<String>();
2803 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2804 if (entry.getValue() != null) {
2805 known.add(entry.getKey());
2806 }
2807 }
2808
2809 if (known.size() > 0) {
2810 list = new String[known.size()];
2811 known.toArray(list);
2812 }
2813 return list;
2814 }
2815
2816 // Select which transport to use for the next backup operation. If the given
2817 // name is not one of the available transports, no action is taken and the method
2818 // returns null.
2819 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002820 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002821
2822 synchronized (mTransports) {
2823 String prevTransport = null;
2824 if (mTransports.get(transport) != null) {
2825 prevTransport = mCurrentTransport;
2826 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002827 Settings.Secure.putString(mContext.getContentResolver(),
2828 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002829 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002830 + " returning " + prevTransport);
2831 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002832 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002833 }
2834 return prevTransport;
2835 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002836 }
2837
Christopher Tatef5e1c292010-12-08 18:40:26 -08002838 // Supply the configuration Intent for the given transport. If the name is not one
2839 // of the available transports, or if the transport does not supply any configuration
2840 // UI, the method returns null.
2841 public Intent getConfigurationIntent(String transportName) {
2842 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2843 "getConfigurationIntent");
2844
2845 synchronized (mTransports) {
2846 final IBackupTransport transport = mTransports.get(transportName);
2847 if (transport != null) {
2848 try {
2849 final Intent intent = transport.configurationIntent();
2850 if (DEBUG) Slog.d(TAG, "getConfigurationIntent() returning config intent "
2851 + intent);
2852 return intent;
2853 } catch (RemoteException e) {
2854 /* fall through to return null */
2855 }
2856 }
2857 }
2858
2859 return null;
2860 }
2861
2862 // Supply the configuration summary string for the given transport. If the name is
2863 // not one of the available transports, or if the transport does not supply any
2864 // summary / destination string, the method can return null.
2865 //
2866 // This string is used VERBATIM as the summary text of the relevant Settings item!
2867 public String getDestinationString(String transportName) {
2868 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2869 "getConfigurationIntent");
2870
2871 synchronized (mTransports) {
2872 final IBackupTransport transport = mTransports.get(transportName);
2873 if (transport != null) {
2874 try {
2875 final String text = transport.currentDestinationString();
2876 if (DEBUG) Slog.d(TAG, "getDestinationString() returning " + text);
2877 return text;
2878 } catch (RemoteException e) {
2879 /* fall through to return null */
2880 }
2881 }
2882 }
2883
2884 return null;
2885 }
2886
Christopher Tate043dadc2009-06-02 16:11:00 -07002887 // Callback: a requested backup agent has been instantiated. This should only
2888 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002889 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002890 synchronized(mAgentConnectLock) {
2891 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002892 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002893 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2894 mConnectedAgent = agent;
2895 mConnecting = false;
2896 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002897 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002898 + " claiming agent connected");
2899 }
2900 mAgentConnectLock.notifyAll();
2901 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002902 }
2903
2904 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2905 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002906 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002907 public void agentDisconnected(String packageName) {
2908 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002909 synchronized(mAgentConnectLock) {
2910 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2911 mConnectedAgent = null;
2912 mConnecting = false;
2913 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002914 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002915 + " claiming agent disconnected");
2916 }
2917 mAgentConnectLock.notifyAll();
2918 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002919 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002920
Christopher Tate1bb69062010-02-19 17:02:12 -08002921 // An application being installed will need a restore pass, then the Package Manager
2922 // will need to be told when the restore is finished.
2923 public void restoreAtInstall(String packageName, int token) {
2924 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002925 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002926 + " attemping install-time restore");
2927 return;
2928 }
2929
2930 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002931 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002932 + " token=" + Integer.toHexString(token));
2933
Christopher Tatef0872722010-02-25 15:22:48 -08002934 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002935 // okay, we're going to attempt a restore of this package from this restore set.
2936 // The eventual message back into the Package Manager to run the post-install
2937 // steps for 'token' will be issued from the restore handling code.
2938
2939 // We can use a synthetic PackageInfo here because:
2940 // 1. We know it's valid, since the Package Manager supplied the name
2941 // 2. Only the packageName field will be used by the restore code
2942 PackageInfo pkg = new PackageInfo();
2943 pkg.packageName = packageName;
2944
2945 mWakelock.acquire();
2946 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2947 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
Chris Tate249345b2010-10-29 12:57:04 -07002948 restoreSet, pkg, token, true);
Christopher Tate1bb69062010-02-19 17:02:12 -08002949 mBackupHandler.sendMessage(msg);
2950 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002951 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2952 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002953 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002954 try {
2955 mPackageManagerBinder.finishPackageInstall(token);
2956 } catch (RemoteException e) { /* can't happen */ }
2957 }
2958 }
2959
Christopher Tate8c850b72009-06-07 19:33:20 -07002960 // Hand off a restore session
Chris Tate44ab8452010-11-16 15:10:49 -08002961 public IRestoreSession beginRestoreSession(String packageName, String transport) {
2962 if (DEBUG) Slog.v(TAG, "beginRestoreSession: pkg=" + packageName
2963 + " transport=" + transport);
2964
2965 boolean needPermission = true;
2966 if (transport == null) {
2967 transport = mCurrentTransport;
2968
2969 if (packageName != null) {
2970 PackageInfo app = null;
2971 try {
2972 app = mPackageManager.getPackageInfo(packageName, 0);
2973 } catch (NameNotFoundException nnf) {
2974 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
2975 throw new IllegalArgumentException("Package " + packageName + " not found");
2976 }
2977
2978 if (app.applicationInfo.uid == Binder.getCallingUid()) {
2979 // So: using the current active transport, and the caller has asked
2980 // that its own package will be restored. In this narrow use case
2981 // we do not require the caller to hold the permission.
2982 needPermission = false;
2983 }
2984 }
2985 }
2986
2987 if (needPermission) {
2988 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2989 "beginRestoreSession");
2990 } else {
2991 if (DEBUG) Slog.d(TAG, "restoring self on current transport; no permission needed");
2992 }
Christopher Tatef68eb502009-06-16 11:02:01 -07002993
2994 synchronized(this) {
2995 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002996 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002997 return null;
2998 }
Chris Tate44ab8452010-11-16 15:10:49 -08002999 mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
Christopher Tate73a3cb32010-12-13 18:27:26 -08003000 mBackupHandler.sendEmptyMessageDelayed(MSG_RESTORE_TIMEOUT, TIMEOUT_RESTORE_INTERVAL);
Christopher Tatef68eb502009-06-16 11:02:01 -07003001 }
3002 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07003003 }
Christopher Tate043dadc2009-06-02 16:11:00 -07003004
Christopher Tate73a3cb32010-12-13 18:27:26 -08003005 void clearRestoreSession(ActiveRestoreSession currentSession) {
3006 synchronized(this) {
3007 if (currentSession != mActiveRestoreSession) {
3008 Slog.e(TAG, "ending non-current restore session");
3009 } else {
3010 if (DEBUG) Slog.v(TAG, "Clearing restore session and halting timeout");
3011 mActiveRestoreSession = null;
3012 mBackupHandler.removeMessages(MSG_RESTORE_TIMEOUT);
3013 }
3014 }
3015 }
3016
Christopher Tate44a27902010-01-27 17:15:49 -08003017 // Note that a currently-active backup agent has notified us that it has
3018 // completed the given outstanding asynchronous backup/restore operation.
3019 public void opComplete(int token) {
3020 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003021 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08003022 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
3023 mCurrentOpLock.notifyAll();
3024 }
3025 }
3026
Christopher Tate9b3905c2009-06-08 15:24:01 -07003027 // ----- Restore session -----
3028
Christopher Tate80202c82010-01-25 19:37:47 -08003029 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07003030 private static final String TAG = "RestoreSession";
3031
Chris Tate44ab8452010-11-16 15:10:49 -08003032 private String mPackageName;
Christopher Tate9b3905c2009-06-08 15:24:01 -07003033 private IBackupTransport mRestoreTransport = null;
3034 RestoreSet[] mRestoreSets = null;
Christopher Tate73a3cb32010-12-13 18:27:26 -08003035 boolean mEnded = false;
Christopher Tate9b3905c2009-06-08 15:24:01 -07003036
Chris Tate44ab8452010-11-16 15:10:49 -08003037 ActiveRestoreSession(String packageName, String transport) {
3038 mPackageName = packageName;
Christopher Tate91717492009-06-26 21:07:13 -07003039 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07003040 }
3041
3042 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07003043 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04003044 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003045 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07003046 if (observer == null) {
3047 throw new IllegalArgumentException("Observer must not be null");
3048 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003049
Christopher Tate73a3cb32010-12-13 18:27:26 -08003050 if (mEnded) {
3051 throw new IllegalStateException("Restore session already ended");
3052 }
3053
Christopher Tate1bb69062010-02-19 17:02:12 -08003054 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07003055 try {
Christopher Tate43383042009-07-13 15:17:13 -07003056 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003057 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07003058 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07003059 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07003060 // spin off the transport request to our service thread
3061 mWakelock.acquire();
3062 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
3063 new RestoreGetSetsParams(mRestoreTransport, this, observer));
3064 mBackupHandler.sendMessage(msg);
3065 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07003066 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003067 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07003068 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08003069 } finally {
3070 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07003071 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07003072 }
3073
Christopher Tate84725812010-02-04 15:52:40 -08003074 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07003075 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
3076 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003077
Chris Tate44ab8452010-11-16 15:10:49 -08003078 if (DEBUG) Slog.d(TAG, "restoreAll token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07003079 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003080
Christopher Tate73a3cb32010-12-13 18:27:26 -08003081 if (mEnded) {
3082 throw new IllegalStateException("Restore session already ended");
3083 }
3084
Dan Egnor0084da52009-07-29 12:57:16 -07003085 if (mRestoreTransport == null || mRestoreSets == null) {
Chris Tate44ab8452010-11-16 15:10:49 -08003086 Slog.e(TAG, "Ignoring restoreAll() with no restore set");
3087 return -1;
3088 }
3089
3090 if (mPackageName != null) {
3091 Slog.e(TAG, "Ignoring restoreAll() on single-package session");
Dan Egnor0084da52009-07-29 12:57:16 -07003092 return -1;
3093 }
3094
Christopher Tate21ab6a52009-09-24 18:01:46 -07003095 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07003096 for (int i = 0; i < mRestoreSets.length; i++) {
3097 if (token == mRestoreSets[i].token) {
3098 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07003099 mWakelock.acquire();
3100 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07003101 msg.obj = new RestoreParams(mRestoreTransport, observer, token, true);
Christopher Tate21ab6a52009-09-24 18:01:46 -07003102 mBackupHandler.sendMessage(msg);
3103 Binder.restoreCallingIdentity(oldId);
3104 return 0;
3105 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07003106 }
3107 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07003108
Joe Onorato8a9b2202010-02-26 18:56:32 -08003109 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07003110 return -1;
3111 }
3112
Christopher Tate84725812010-02-04 15:52:40 -08003113 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003114 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08003115
Christopher Tate73a3cb32010-12-13 18:27:26 -08003116 if (mEnded) {
3117 throw new IllegalStateException("Restore session already ended");
3118 }
3119
Chris Tate44ab8452010-11-16 15:10:49 -08003120 if (mPackageName != null) {
3121 if (! mPackageName.equals(packageName)) {
3122 Slog.e(TAG, "Ignoring attempt to restore pkg=" + packageName
3123 + " on session for package " + mPackageName);
3124 return -1;
3125 }
3126 }
3127
Christopher Tate84725812010-02-04 15:52:40 -08003128 PackageInfo app = null;
3129 try {
3130 app = mPackageManager.getPackageInfo(packageName, 0);
3131 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003132 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08003133 return -1;
3134 }
3135
3136 // If the caller is not privileged and is not coming from the target
3137 // app's uid, throw a permission exception back to the caller.
3138 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
3139 Binder.getCallingPid(), Binder.getCallingUid());
3140 if ((perm == PackageManager.PERMISSION_DENIED) &&
3141 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003142 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08003143 + " or calling uid=" + Binder.getCallingUid());
3144 throw new SecurityException("No permission to restore other packages");
3145 }
3146
Christopher Tate7d411a32010-02-26 11:27:08 -08003147 // If the package has no backup agent, we obviously cannot proceed
3148 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003149 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08003150 return -1;
3151 }
3152
Christopher Tate84725812010-02-04 15:52:40 -08003153 // So far so good; we're allowed to try to restore this package. Now
3154 // check whether there is data for it in the current dataset, falling back
3155 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08003156 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08003157
3158 // If we didn't come up with a place to look -- no ancestral dataset and
3159 // the app has never been backed up from this device -- there's nothing
3160 // to do but return failure.
3161 if (token == 0) {
Chris Tate44ab8452010-11-16 15:10:49 -08003162 if (DEBUG) Slog.w(TAG, "No data available for this package; not restoring");
Christopher Tate84725812010-02-04 15:52:40 -08003163 return -1;
3164 }
3165
3166 // Ready to go: enqueue the restore request and claim success
3167 long oldId = Binder.clearCallingIdentity();
3168 mWakelock.acquire();
3169 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Chris Tate249345b2010-10-29 12:57:04 -07003170 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0, false);
Christopher Tate84725812010-02-04 15:52:40 -08003171 mBackupHandler.sendMessage(msg);
3172 Binder.restoreCallingIdentity(oldId);
3173 return 0;
3174 }
3175
Christopher Tate73a3cb32010-12-13 18:27:26 -08003176 // Posted to the handler to tear down a restore session in a cleanly synchronized way
3177 class EndRestoreRunnable implements Runnable {
3178 BackupManagerService mBackupManager;
3179 ActiveRestoreSession mSession;
3180
3181 EndRestoreRunnable(BackupManagerService manager, ActiveRestoreSession session) {
3182 mBackupManager = manager;
3183 mSession = session;
3184 }
3185
3186 public void run() {
3187 // clean up the session's bookkeeping
3188 synchronized (mSession) {
3189 try {
3190 if (mSession.mRestoreTransport != null) {
3191 mSession.mRestoreTransport.finishRestore();
3192 }
3193 } catch (Exception e) {
3194 Slog.e(TAG, "Error in finishRestore", e);
3195 } finally {
3196 mSession.mRestoreTransport = null;
3197 mSession.mEnded = true;
3198 }
3199 }
3200
3201 // clean up the BackupManagerService side of the bookkeeping
3202 // and cancel any pending timeout message
3203 mBackupManager.clearRestoreSession(mSession);
3204 }
3205 }
3206
Dan Egnor0084da52009-07-29 12:57:16 -07003207 public synchronized void endRestoreSession() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003208 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04003209
Christopher Tate73a3cb32010-12-13 18:27:26 -08003210 if (mEnded) {
3211 throw new IllegalStateException("Restore session already ended");
Dan Egnor0084da52009-07-29 12:57:16 -07003212 }
3213
Christopher Tate73a3cb32010-12-13 18:27:26 -08003214 mBackupHandler.post(new EndRestoreRunnable(BackupManagerService.this, this));
Christopher Tate9b3905c2009-06-08 15:24:01 -07003215 }
3216 }
3217
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003218 @Override
3219 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003220 long identityToken = Binder.clearCallingIdentity();
3221 try {
3222 dumpInternal(pw);
3223 } finally {
3224 Binder.restoreCallingIdentity(identityToken);
3225 }
3226 }
3227
3228 private void dumpInternal(PrintWriter pw) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003229 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07003230 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07003231 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08003232 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08003233 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07003234 pw.println("Last backup pass: " + mLastBackupPass
3235 + " (now = " + System.currentTimeMillis() + ')');
3236 pw.println(" next scheduled: " + mNextBackupPass);
3237
Christopher Tate91717492009-06-26 21:07:13 -07003238 pw.println("Available transports:");
3239 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07003240 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
3241 try {
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003242 IBackupTransport transport = getTransport(t);
3243 File dir = new File(mBaseStateDir, transport.transportDirName());
3244 pw.println(" destination: " + transport.currentDestinationString());
3245 pw.println(" intent: " + transport.configurationIntent());
Dan Egnor852f8e42009-09-30 11:20:45 -07003246 for (File f : dir.listFiles()) {
3247 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
3248 }
Fabrice Di Meglio8aac3ee2011-01-12 18:47:14 -08003249 } catch (Exception e) {
3250 Slog.e(TAG, "Error in transport", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07003251 pw.println(" Error: " + e);
3252 }
Christopher Tate91717492009-06-26 21:07:13 -07003253 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003254
3255 pw.println("Pending init: " + mPendingInits.size());
3256 for (String s : mPendingInits) {
3257 pw.println(" " + s);
3258 }
3259
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003260 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07003261 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003262 for (int i=0; i<N; i++) {
3263 int uid = mBackupParticipants.keyAt(i);
3264 pw.print(" uid: ");
3265 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003266 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
3267 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07003268 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003269 }
3270 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003271
Christopher Tateb49ceb32010-02-08 16:22:24 -08003272 pw.println("Ancestral packages: "
3273 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07003274 if (mAncestralPackages != null) {
3275 for (String pkg : mAncestralPackages) {
3276 pw.println(" " + pkg);
3277 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08003278 }
3279
Christopher Tate73e02522009-07-15 14:18:26 -07003280 pw.println("Ever backed up: " + mEverStoredApps.size());
3281 for (String pkg : mEverStoredApps) {
3282 pw.println(" " + pkg);
3283 }
Christopher Tate55f931a2009-09-29 17:17:34 -07003284
3285 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07003286 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07003287 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07003288 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07003289 }
3290 }
Christopher Tate487529a2009-04-29 14:03:25 -07003291}