blob: f871496ff4b9d1e47d56bd1efc412bf86dc4fd5a [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;
20import android.app.IActivityManager;
21import android.app.IApplicationThread;
22import android.app.IBackupAgent;
Christopher Tate3799bc22009-05-06 16:13:56 -070023import android.content.BroadcastReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -070024import android.content.Context;
25import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070026import android.content.IntentFilter;
Christopher Tate181fafa2009-05-14 11:12:14 -070027import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070028import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070029import android.content.pm.PackageInfo;
Christopher Tate487529a2009-04-29 14:03:25 -070030import android.content.pm.PackageManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070031import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070032import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070033import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070035import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070036import android.os.Handler;
37import android.os.IBinder;
38import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070039import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070040import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070041import android.os.RemoteException;
42import android.util.Log;
43import android.util.SparseArray;
44
45import android.backup.IBackupManager;
Christopher Tate8c850b72009-06-07 19:33:20 -070046import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070047import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070048import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070049
50import com.android.internal.backup.AdbTransport;
51import com.android.internal.backup.GoogleTransport;
52import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070053
Christopher Tate22b87872009-05-04 16:41:53 -070054import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070055import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070056import java.io.FileNotFoundException;
Christopher Tatec7b31e32009-06-10 15:49:30 -070057import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070058import java.io.PrintWriter;
Christopher Tate487529a2009-04-29 14:03:25 -070059import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040060import java.util.ArrayList;
61import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070062import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070063import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070064import java.util.List;
65
66class BackupManagerService extends IBackupManager.Stub {
67 private static final String TAG = "BackupManagerService";
68 private static final boolean DEBUG = true;
69
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070070 private static final long COLLECTION_INTERVAL = 1000;
71 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070072
73 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070074 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tatec7b31e32009-06-10 15:49:30 -070075
76 // Timeout interval for deciding that a bind or clear-data has taken too long
77 static final long TIMEOUT_INTERVAL = 10 * 1000;
78
Christopher Tate487529a2009-04-29 14:03:25 -070079 private Context mContext;
80 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070081 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070082 private final BackupHandler mBackupHandler = new BackupHandler();
83 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070084 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
85 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070086 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070087 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070088 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070089 public boolean fullBackup;
90
Christopher Tate181fafa2009-05-14 11:12:14 -070091 BackupRequest(ApplicationInfo app, boolean isFull) {
92 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -070093 fullBackup = isFull;
94 }
Christopher Tate181fafa2009-05-14 11:12:14 -070095
96 public String toString() {
97 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
98 }
Christopher Tate46758122009-05-06 11:22:00 -070099 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400100 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700101 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
102 = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400103 // Backups that we have started. These are separate to prevent starvation
104 // if an app keeps re-enqueuing itself.
105 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -0700106 private final Object mQueueLock = new Object();
107
Christopher Tate043dadc2009-06-02 16:11:00 -0700108 // The thread performing the sequence of queued backups binds to each app's agent
109 // in succession. Bind notifications are asynchronously delivered through the
110 // Activity Manager; use this lock object to signal when a requested binding has
111 // completed.
112 private final Object mAgentConnectLock = new Object();
113 private IBackupAgent mConnectedAgent;
114 private volatile boolean mConnecting;
115
Christopher Tatec7b31e32009-06-10 15:49:30 -0700116 // A similar synchronicity mechanism around clearing apps' data for restore
117 private final Object mClearDataLock = new Object();
118 private volatile boolean mClearingData;
119
Christopher Tate043dadc2009-06-02 16:11:00 -0700120 private int mTransportId;
121
Christopher Tate22b87872009-05-04 16:41:53 -0700122 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700123 private File mDataDir;
Christopher Tate487529a2009-04-29 14:03:25 -0700124
Christopher Tate487529a2009-04-29 14:03:25 -0700125 public BackupManagerService(Context context) {
126 mContext = context;
127 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700128 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700129
Christopher Tate22b87872009-05-04 16:41:53 -0700130 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700131 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700132 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700133 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate043dadc2009-06-02 16:11:00 -0700134 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Christopher Tate22b87872009-05-04 16:41:53 -0700135
Christopher Tate3799bc22009-05-06 16:13:56 -0700136 // Build our mapping of uid to backup client services
137 synchronized (mBackupParticipants) {
138 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700139 }
140
Christopher Tate3799bc22009-05-06 16:13:56 -0700141 // Register for broadcasts about package install, etc., so we can
142 // update the provider list.
143 IntentFilter filter = new IntentFilter();
144 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
145 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
146 filter.addDataScheme("package");
147 mContext.registerReceiver(mBroadcastReceiver, filter);
148 }
149
150 // ----- Track installation/removal of packages -----
151 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
152 public void onReceive(Context context, Intent intent) {
153 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
154
155 Uri uri = intent.getData();
156 if (uri == null) {
157 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700158 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700159 String pkgName = uri.getSchemeSpecificPart();
160 if (pkgName == null) {
161 return;
162 }
163
164 String action = intent.getAction();
165 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
166 synchronized (mBackupParticipants) {
167 Bundle extras = intent.getExtras();
168 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
169 // The package was just upgraded
170 updatePackageParticipantsLocked(pkgName);
171 } else {
172 // The package was just added
173 addPackageParticipantsLocked(pkgName);
174 }
175 }
176 }
177 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
178 Bundle extras = intent.getExtras();
179 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
180 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
181 } else {
182 synchronized (mBackupParticipants) {
183 removePackageParticipantsLocked(pkgName);
184 }
185 }
186 }
187 }
188 };
189
Joe Onorato8ad02812009-05-13 01:41:44 -0400190 // ----- Run the actual backup process asynchronously -----
191
Christopher Tate181fafa2009-05-14 11:12:14 -0700192 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400193 public void handleMessage(Message msg) {
194
195 switch (msg.what) {
196 case MSG_RUN_BACKUP:
197 // snapshot the pending-backup set and work on that
198 synchronized (mQueueLock) {
Joe Onoratod2110db2009-05-19 13:41:21 -0700199 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700200 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700201 for (BackupRequest b: mPendingBackups.values()) {
202 mBackupQueue.add(b);
203 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700204 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400205 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400206 // !!! TODO: start a new backup-queue journal file too
207 // WARNING: If we crash after this line, anything in mPendingBackups will
208 // be lost. FIX THIS.
209 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700210 (new PerformBackupThread(mTransportId, mBackupQueue)).run();
211 break;
212
213 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400214 break;
215 }
216 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400217 }
218
Christopher Tate181fafa2009-05-14 11:12:14 -0700219 // Add the backup agents in the given package to our set of known backup participants.
220 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700221 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700222 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700223 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700224 List<ApplicationInfo> targetApps = allAgentApps();
225 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700226 }
227
Christopher Tate181fafa2009-05-14 11:12:14 -0700228 private void addPackageParticipantsLockedInner(String packageName,
229 List<ApplicationInfo> targetApps) {
230 if (DEBUG) {
231 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
232 for (ApplicationInfo a : targetApps) {
233 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
234 }
235 }
236
237 for (ApplicationInfo app : targetApps) {
238 if (packageName == null || app.packageName.equals(packageName)) {
239 int uid = app.uid;
240 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700241 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700242 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700243 mBackupParticipants.put(uid, set);
244 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700245 set.add(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700246 }
Christopher Tate487529a2009-04-29 14:03:25 -0700247 }
248 }
249
Christopher Tate3799bc22009-05-06 16:13:56 -0700250 // Remove the given package's backup services from our known active set. If
251 // 'packageName' is null, *all* backup services will be removed.
252 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700253 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700254 List<ApplicationInfo> allApps = null;
255 if (packageName != null) {
256 allApps = new ArrayList<ApplicationInfo>();
257 try {
258 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
259 allApps.add(app);
260 } catch (Exception e) {
261 // just skip it
262 }
263 } else {
264 // all apps with agents
265 allApps = allAgentApps();
266 }
267 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700268 }
269
Joe Onorato8ad02812009-05-13 01:41:44 -0400270 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700271 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700272 if (DEBUG) {
273 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
274 + ") removing " + agents.size() + " entries");
275 for (ApplicationInfo a : agents) {
276 Log.v(TAG, " - " + a);
277 }
278 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700279 for (ApplicationInfo app : agents) {
280 if (packageName == null || app.packageName.equals(packageName)) {
281 int uid = app.uid;
282 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700283 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700284 // Find the existing entry with the same package name, and remove it.
285 // We can't just remove(app) because the instances are different.
286 for (ApplicationInfo entry: set) {
287 if (entry.packageName.equals(app.packageName)) {
288 set.remove(entry);
289 break;
290 }
291 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700292 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700293 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700294 }
295 }
296 }
297 }
298
Christopher Tate181fafa2009-05-14 11:12:14 -0700299 // Returns the set of all applications that define an android:backupAgent attribute
300 private List<ApplicationInfo> allAgentApps() {
301 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
302 int N = allApps.size();
303 if (N > 0) {
304 for (int a = N-1; a >= 0; a--) {
305 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700306 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
307 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700308 allApps.remove(a);
309 }
310 }
311 }
312 return allApps;
313 }
314
Christopher Tate3799bc22009-05-06 16:13:56 -0700315 // Reset the given package's known backup participants. Unlike add/remove, the update
316 // action cannot be passed a null package name.
317 void updatePackageParticipantsLocked(String packageName) {
318 if (packageName == null) {
319 Log.e(TAG, "updatePackageParticipants called with null package name");
320 return;
321 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700322 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700323
324 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700325 List<ApplicationInfo> allApps = allAgentApps();
326 removePackageParticipantsLockedInner(packageName, allApps);
327 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700328 }
329
Christopher Tate8c850b72009-06-07 19:33:20 -0700330 // Instantiate the given transport
331 private IBackupTransport createTransport(int transportID) {
332 IBackupTransport transport = null;
333 switch (transportID) {
334 case BackupManager.TRANSPORT_ADB:
335 if (DEBUG) Log.v(TAG, "Initializing adb transport");
336 transport = new AdbTransport();
337 break;
338
339 case BackupManager.TRANSPORT_GOOGLE:
340 if (DEBUG) Log.v(TAG, "Initializing Google transport");
341 //!!! TODO: stand up the google backup transport for real here
342 transport = new GoogleTransport();
343 break;
344
345 default:
346 Log.e(TAG, "creating unknown transport " + transportID);
347 }
348 return transport;
349 }
350
Christopher Tatedf01dea2009-06-09 20:45:02 -0700351 // fire off a backup agent, blocking until it attaches or times out
352 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
353 IBackupAgent agent = null;
354 synchronized(mAgentConnectLock) {
355 mConnecting = true;
356 mConnectedAgent = null;
357 try {
358 if (mActivityManager.bindBackupAgent(app, mode)) {
359 Log.d(TAG, "awaiting agent for " + app);
360
361 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700362 // only wait 10 seconds for the clear data to happen
363 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
364 while (mConnecting && mConnectedAgent == null
365 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700366 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700367 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700368 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700369 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700370 return null;
371 }
372 }
373
374 // if we timed out with no connect, abort and move on
375 if (mConnecting == true) {
376 Log.w(TAG, "Timeout waiting for agent " + app);
377 return null;
378 }
379 agent = mConnectedAgent;
380 }
381 } catch (RemoteException e) {
382 // can't happen
383 }
384 }
385 return agent;
386 }
387
Christopher Tatec7b31e32009-06-10 15:49:30 -0700388 // clear an application's data, blocking until the operation completes or times out
389 void clearApplicationDataSynchronous(String packageName) {
390 ClearDataObserver observer = new ClearDataObserver();
391
392 synchronized(mClearDataLock) {
393 mClearingData = true;
394 mPackageManager.clearApplicationUserData(packageName, observer);
395
396 // only wait 10 seconds for the clear data to happen
397 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
398 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
399 try {
400 mClearDataLock.wait(5000);
401 } catch (InterruptedException e) {
402 // won't happen, but still.
403 mClearingData = false;
404 }
405 }
406 }
407 }
408
409 class ClearDataObserver extends IPackageDataObserver.Stub {
410 public void onRemoveCompleted(String packageName, boolean succeeded)
411 throws android.os.RemoteException {
412 synchronized(mClearDataLock) {
413 mClearingData = false;
414 notifyAll();
415 }
416 }
417 }
418
Christopher Tate043dadc2009-06-02 16:11:00 -0700419 // ----- Back up a set of applications via a worker thread -----
420
421 class PerformBackupThread extends Thread {
422 private static final String TAG = "PerformBackupThread";
423 int mTransport;
424 ArrayList<BackupRequest> mQueue;
425
426 public PerformBackupThread(int transportId, ArrayList<BackupRequest> queue) {
427 mTransport = transportId;
428 mQueue = queue;
429 }
430
431 @Override
432 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700433 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
434
435 // stand up the current transport
Christopher Tate8c850b72009-06-07 19:33:20 -0700436 IBackupTransport transport = createTransport(mTransport);
437 if (transport == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700438 return;
439 }
440
Christopher Tatedf01dea2009-06-09 20:45:02 -0700441 // start up the transport
442 try {
443 transport.startSession();
444 } catch (Exception e) {
445 Log.e(TAG, "Error session transport");
446 e.printStackTrace();
447 return;
448 }
449
Christopher Tate043dadc2009-06-02 16:11:00 -0700450 // The transport is up and running; now run all the backups in our queue
451 doQueuedBackups(transport);
452
453 // Finally, tear down the transport
454 try {
455 transport.endSession();
456 } catch (Exception e) {
457 Log.e(TAG, "Error ending transport");
458 e.printStackTrace();
459 }
460 }
461
462 private void doQueuedBackups(IBackupTransport transport) {
463 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700464 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700465
466 IBackupAgent agent = null;
467 int mode = (request.fullBackup)
468 ? IApplicationThread.BACKUP_MODE_FULL
469 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
470 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700471 agent = bindToAgentSynchronous(request.appInfo, mode);
472 if (agent != null) {
473 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700474 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700475
476 // unbind even on timeout, just in case
477 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700478 } catch (SecurityException ex) {
479 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700480 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700481 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700482 Log.v(TAG, "bind/backup threw");
483 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700484 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700485
Christopher Tate043dadc2009-06-02 16:11:00 -0700486 }
487 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700488
489 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
490 final String packageName = request.appInfo.packageName;
491 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
492
493 try {
494 // Look up the package info & signatures. This is first so that if it
495 // throws an exception, there's no file setup yet that would need to
496 // be unraveled.
497 PackageInfo packInfo = mPackageManager.getPackageInfo(packageName,
498 PackageManager.GET_SIGNATURES);
499
500 // !!! TODO: get the state file dir from the transport
501 File savedStateName = new File(mStateDir, packageName);
502 File backupDataName = new File(mDataDir, packageName + ".data");
503 File newStateName = new File(mStateDir, packageName + ".new");
504
505 // In a full backup, we pass a null ParcelFileDescriptor as
506 // the saved-state "file"
507 ParcelFileDescriptor savedState = (request.fullBackup) ? null
508 : ParcelFileDescriptor.open(savedStateName,
509 ParcelFileDescriptor.MODE_READ_ONLY |
510 ParcelFileDescriptor.MODE_CREATE);
511
512 backupDataName.delete();
513 ParcelFileDescriptor backupData =
514 ParcelFileDescriptor.open(backupDataName,
515 ParcelFileDescriptor.MODE_READ_WRITE |
516 ParcelFileDescriptor.MODE_CREATE);
517
518 newStateName.delete();
519 ParcelFileDescriptor newState =
520 ParcelFileDescriptor.open(newStateName,
521 ParcelFileDescriptor.MODE_READ_WRITE |
522 ParcelFileDescriptor.MODE_CREATE);
523
524 // Run the target's backup pass
525 boolean success = false;
526 try {
527 agent.doBackup(savedState, backupData, newState);
528 success = true;
529 } finally {
530 if (savedState != null) {
531 savedState.close();
532 }
533 backupData.close();
534 newState.close();
535 }
536
537 // Now propagate the newly-backed-up data to the transport
538 if (success) {
539 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
540 backupData =
541 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
542 int error = transport.performBackup(packInfo, backupData);
543
544 // !!! TODO: After successful transport, delete the now-stale data
545 // and juggle the files so that next time the new state is passed
546 //backupDataName.delete();
547 newStateName.renameTo(savedStateName);
548 }
549 } catch (NameNotFoundException e) {
550 Log.e(TAG, "Package not found on backup: " + packageName);
551 } catch (FileNotFoundException fnf) {
552 Log.w(TAG, "File not found on backup: ");
553 fnf.printStackTrace();
554 } catch (RemoteException e) {
555 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
556 e.printStackTrace();
557 } catch (Exception e) {
558 Log.w(TAG, "Final exception guard in backup: ");
559 e.printStackTrace();
560 }
561 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700562 }
563
Christopher Tatedf01dea2009-06-09 20:45:02 -0700564
565 // ----- Restore handling -----
566
567 // Is the given package restorable on this device? Returns the on-device app's
568 // ApplicationInfo struct if it is; null if not.
569 //
570 // !!! TODO: also consider signatures
Christopher Tatec7b31e32009-06-10 15:49:30 -0700571 PackageInfo isRestorable(PackageInfo packageInfo) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700572 if (packageInfo.packageName != null) {
573 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700574 PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
Christopher Tatedf01dea2009-06-09 20:45:02 -0700575 PackageManager.GET_SIGNATURES);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700576 if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700577 return app;
578 }
579 } catch (Exception e) {
580 // doesn't exist on this device, or other error -- just ignore it.
581 }
582 }
583 return null;
584 }
585
586 class PerformRestoreThread extends Thread {
587 private IBackupTransport mTransport;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700588 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700589
590 PerformRestoreThread(IBackupTransport transport) {
591 mTransport = transport;
592 }
593
594 @Override
595 public void run() {
596 /**
597 * Restore sequence:
598 *
599 * 1. start up the transport session
600 * 2. get the restore set description for our identity
601 * 3. for each app in the restore set:
602 * 3.a. if it's restorable on this device, add it to the restore queue
603 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700604 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700605 * 4.b. get the restore data for the app from the transport
606 * 4.c. launch the backup agent for the app
607 * 4.d. agent.doRestore() with the data from the server
608 * 4.e. unbind the agent [and kill the app?]
609 * 5. shut down the transport
610 */
611
612 int err = -1;
613 try {
614 err = mTransport.startSession();
615 } catch (Exception e) {
616 Log.e(TAG, "Error starting transport for restore");
617 e.printStackTrace();
618 }
619
620 if (err == 0) {
621 // build the set of apps to restore
622 try {
623 RestoreSet[] images = mTransport.getAvailableRestoreSets();
624 if (images.length > 0) {
625 // !!! for now we always take the first set
Christopher Tatec7b31e32009-06-10 15:49:30 -0700626 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700627
628 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700629 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
630 HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700631 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700632 // get the real PackageManager idea of the package
633 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700634 if (app != null) {
635 appsToRestore.add(app);
636 }
637 }
638
639 // now run the restore queue
640 doQueuedRestores(appsToRestore);
641 }
642 } catch (RemoteException e) {
643 // can't happen; transports run locally
644 }
645
646 // done; shut down the transport
647 try {
648 mTransport.endSession();
649 } catch (Exception e) {
650 Log.e(TAG, "Error ending transport for restore");
651 e.printStackTrace();
652 }
653 }
654
655 // even if the initial session startup failed, report that we're done here
656 }
657
658 // restore each app in the queue
Christopher Tatec7b31e32009-06-10 15:49:30 -0700659 void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
660 for (PackageInfo app : appsToRestore) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700661 Log.d(TAG, "starting agent for restore of " + app);
662
Christopher Tatedf01dea2009-06-09 20:45:02 -0700663 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700664 // Remove the app's data first
665 clearApplicationDataSynchronous(app.packageName);
666
667 // Now perform the restore into the clean app
668 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
669 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700670 if (agent != null) {
671 processOneRestore(app, agent);
672 }
673
674 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700675 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700676 } catch (SecurityException ex) {
677 // Try for the next one.
678 Log.d(TAG, "error in bind", ex);
679 } catch (RemoteException e) {
680 // can't happen
681 }
682
683 }
684 }
685
Christopher Tatec7b31e32009-06-10 15:49:30 -0700686 // Do the guts of a restore of one application, derived from the 'mImage'
687 // restore set via the 'mTransport' transport.
688 void processOneRestore(PackageInfo app, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700689 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700690 final String packageName = app.packageName;
691
692 // !!! TODO: get the dirs from the transport
693 File backupDataName = new File(mDataDir, packageName + ".restore");
694 backupDataName.delete();
695 try {
696 ParcelFileDescriptor backupData =
697 ParcelFileDescriptor.open(backupDataName,
698 ParcelFileDescriptor.MODE_READ_WRITE |
699 ParcelFileDescriptor.MODE_CREATE);
700
701 // Run the transport's restore pass
702 // Run the target's backup pass
703 int err = -1;
704 try {
705 err = mTransport.getRestoreData(mImage.token, app, backupData);
706 } catch (RemoteException e) {
707 // can't happen
708 } finally {
709 backupData.close();
710 }
711
712 // Okay, we have the data. Now have the agent do the restore.
713 File newStateName = new File(mStateDir, packageName + ".new");
714 ParcelFileDescriptor newState =
715 ParcelFileDescriptor.open(newStateName,
716 ParcelFileDescriptor.MODE_READ_WRITE |
717 ParcelFileDescriptor.MODE_CREATE);
718
719 backupData = ParcelFileDescriptor.open(backupDataName,
720 ParcelFileDescriptor.MODE_READ_ONLY);
721
722 boolean success = false;
723 try {
724 agent.doRestore(backupData, newState);
725 success = true;
726 } catch (Exception e) {
727 Log.e(TAG, "Restore failed for " + packageName);
728 e.printStackTrace();
729 } finally {
730 newState.close();
731 backupData.close();
732 }
733
734 // if everything went okay, remember the recorded state now
735 if (success) {
736 File savedStateName = new File(mStateDir, packageName);
737 newStateName.renameTo(savedStateName);
738 }
739 } catch (FileNotFoundException fnfe) {
740 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
741 } catch (IOException ioe) {
742 Log.e(TAG, "Unable to process restore file: " + ioe);
743 } catch (Exception e) {
744 Log.e(TAG, "Final exception guard in restore:");
745 e.printStackTrace();
746 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700747 }
748 }
749
750
Christopher Tate487529a2009-04-29 14:03:25 -0700751 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700752
Christopher Tatea8bf8152009-04-30 11:36:21 -0700753 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700754 // Record that we need a backup pass for the caller. Since multiple callers
755 // may share a uid, we need to note all candidates within that uid and schedule
756 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700757
758 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700759
Christopher Tate181fafa2009-05-14 11:12:14 -0700760 HashSet<ApplicationInfo> targets = mBackupParticipants.get(Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -0700761 if (targets != null) {
762 synchronized (mQueueLock) {
763 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -0700764 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -0700765 // validate the caller-supplied package name against the known set of
766 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -0700767 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -0400768 // Add the caller to the set of pending backups. If there is
769 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -0700770 BackupRequest req = new BackupRequest(app, false);
771 mPendingBackups.put(app, req);
Joe Onorato8ad02812009-05-13 01:41:44 -0400772 // !!! TODO: write to the pending-backup journal file in case of crash
Christopher Tate487529a2009-04-29 14:03:25 -0700773 }
774 }
775
Christopher Tate181fafa2009-05-14 11:12:14 -0700776 if (DEBUG) {
777 int numKeys = mPendingBackups.size();
778 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
779 for (BackupRequest b : mPendingBackups.values()) {
780 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
781 }
782 }
Christopher Tate487529a2009-04-29 14:03:25 -0700783 // Schedule a backup pass in a few minutes. As backup-eligible data
784 // keeps changing, continue to defer the backup pass until things
785 // settle down, to avoid extra overhead.
Christopher Tate043dadc2009-06-02 16:11:00 -0700786 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate487529a2009-04-29 14:03:25 -0700787 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
788 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700789 } else {
790 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700791 }
792 }
Christopher Tate46758122009-05-06 11:22:00 -0700793
Christopher Tate043dadc2009-06-02 16:11:00 -0700794 // Schedule a backup pass for a given package. This method will schedule a
795 // full backup even for apps that do not declare an android:backupAgent, so
796 // use with care.
Christopher Tate46758122009-05-06 11:22:00 -0700797 public void scheduleFullBackup(String packageName) throws RemoteException {
Christopher Tate043dadc2009-06-02 16:11:00 -0700798 mContext.enforceCallingPermission("android.permission.BACKUP", "scheduleFullBackup");
799
800 if (DEBUG) Log.v(TAG, "Scheduling immediate full backup for " + packageName);
Christopher Tate46758122009-05-06 11:22:00 -0700801 synchronized (mQueueLock) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700802 try {
803 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
804 mPendingBackups.put(app, new BackupRequest(app, true));
805 mBackupHandler.sendEmptyMessage(MSG_RUN_FULL_BACKUP);
806 } catch (NameNotFoundException e) {
807 Log.w(TAG, "Could not find app for " + packageName + " to schedule full backup");
Christopher Tate46758122009-05-06 11:22:00 -0700808 }
809 }
810 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700811
Christopher Tate043dadc2009-06-02 16:11:00 -0700812 // Select which transport to use for the next backup operation
813 public int selectBackupTransport(int transportId) {
814 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
815
816 int prevTransport = mTransportId;
817 mTransportId = transportId;
818 return prevTransport;
819 }
820
821 // Callback: a requested backup agent has been instantiated. This should only
822 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700823 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700824 synchronized(mAgentConnectLock) {
825 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
826 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
827 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
828 mConnectedAgent = agent;
829 mConnecting = false;
830 } else {
831 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
832 + " claiming agent connected");
833 }
834 mAgentConnectLock.notifyAll();
835 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700836 }
837
838 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
839 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -0700840 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700841 public void agentDisconnected(String packageName) {
842 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -0700843 synchronized(mAgentConnectLock) {
844 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
845 mConnectedAgent = null;
846 mConnecting = false;
847 } else {
848 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
849 + " claiming agent disconnected");
850 }
851 mAgentConnectLock.notifyAll();
852 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700853 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700854
Christopher Tate8c850b72009-06-07 19:33:20 -0700855 // Hand off a restore session
856 public IRestoreSession beginRestoreSession(int transportID) {
857 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
858 return null;
859 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700860
Christopher Tate9b3905c2009-06-08 15:24:01 -0700861 // ----- Restore session -----
862
863 class RestoreSession extends IRestoreSession.Stub {
864 private IBackupTransport mRestoreTransport = null;
865 RestoreSet[] mRestoreSets = null;
866
867 RestoreSession(int transportID) {
868 mRestoreTransport = createTransport(transportID);
869 }
870
871 // --- Binder interface ---
872 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
873 synchronized(this) {
874 if (mRestoreSets == null) {
875 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
876 }
877 return mRestoreSets;
878 }
879 }
880
881 public int performRestore(int token) throws android.os.RemoteException {
882 return -1;
883 }
884
885 public void endRestoreSession() throws android.os.RemoteException {
886 mRestoreTransport.endSession();
887 mRestoreTransport = null;
888 }
889 }
890
Christopher Tate043dadc2009-06-02 16:11:00 -0700891
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700892 @Override
893 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
894 synchronized (mQueueLock) {
895 int N = mBackupParticipants.size();
896 pw.println("Participants:");
897 for (int i=0; i<N; i++) {
898 int uid = mBackupParticipants.keyAt(i);
899 pw.print(" uid: ");
900 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700901 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
902 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700903 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -0700904 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700905 }
906 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700907 pw.println("Pending:");
908 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
909 while (br.hasNext()) {
910 pw.print(" ");
911 pw.println(br);
912 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700913 }
914 }
Christopher Tate487529a2009-04-29 14:03:25 -0700915}