blob: 42a895c1ac50c78e74d1b546a4e6998ecad70da5 [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 Tate7b881282009-06-07 13:52:37 -070028import android.content.pm.PackageInfo;
Christopher Tate487529a2009-04-29 14:03:25 -070029import android.content.pm.PackageManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070030import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070031import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070032import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070033import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070034import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070035import android.os.Handler;
36import android.os.IBinder;
37import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070038import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070039import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070040import android.os.RemoteException;
41import android.util.Log;
42import android.util.SparseArray;
43
44import android.backup.IBackupManager;
Christopher Tate8c850b72009-06-07 19:33:20 -070045import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070046import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070047import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070048
49import com.android.internal.backup.AdbTransport;
50import com.android.internal.backup.GoogleTransport;
51import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070052
Christopher Tate22b87872009-05-04 16:41:53 -070053import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070054import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070055import java.io.FileNotFoundException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070056import java.io.PrintWriter;
Christopher Tate487529a2009-04-29 14:03:25 -070057import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040058import java.util.ArrayList;
59import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070060import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070061import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070062import java.util.List;
63
64class BackupManagerService extends IBackupManager.Stub {
65 private static final String TAG = "BackupManagerService";
66 private static final boolean DEBUG = true;
67
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068 private static final long COLLECTION_INTERVAL = 1000;
69 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070070
71 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070072 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate487529a2009-04-29 14:03:25 -070073
74 private Context mContext;
75 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070076 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070077 private final BackupHandler mBackupHandler = new BackupHandler();
78 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070079 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
80 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070081 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070082 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070083 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070084 public boolean fullBackup;
85
Christopher Tate181fafa2009-05-14 11:12:14 -070086 BackupRequest(ApplicationInfo app, boolean isFull) {
87 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -070088 fullBackup = isFull;
89 }
Christopher Tate181fafa2009-05-14 11:12:14 -070090
91 public String toString() {
92 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
93 }
Christopher Tate46758122009-05-06 11:22:00 -070094 }
Joe Onorato8ad02812009-05-13 01:41:44 -040095 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -070096 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
97 = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -040098 // Backups that we have started. These are separate to prevent starvation
99 // if an app keeps re-enqueuing itself.
100 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -0700101 private final Object mQueueLock = new Object();
102
Christopher Tate043dadc2009-06-02 16:11:00 -0700103 // The thread performing the sequence of queued backups binds to each app's agent
104 // in succession. Bind notifications are asynchronously delivered through the
105 // Activity Manager; use this lock object to signal when a requested binding has
106 // completed.
107 private final Object mAgentConnectLock = new Object();
108 private IBackupAgent mConnectedAgent;
109 private volatile boolean mConnecting;
110
111 private int mTransportId;
112
Christopher Tate22b87872009-05-04 16:41:53 -0700113 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700114 private File mDataDir;
Christopher Tate487529a2009-04-29 14:03:25 -0700115
Christopher Tate487529a2009-04-29 14:03:25 -0700116 public BackupManagerService(Context context) {
117 mContext = context;
118 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700119 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700120
Christopher Tate22b87872009-05-04 16:41:53 -0700121 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700122 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700123 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700124 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate043dadc2009-06-02 16:11:00 -0700125 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Christopher Tate22b87872009-05-04 16:41:53 -0700126
Christopher Tate3799bc22009-05-06 16:13:56 -0700127 // Build our mapping of uid to backup client services
128 synchronized (mBackupParticipants) {
129 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700130 }
131
Christopher Tate3799bc22009-05-06 16:13:56 -0700132 // Register for broadcasts about package install, etc., so we can
133 // update the provider list.
134 IntentFilter filter = new IntentFilter();
135 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
136 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
137 filter.addDataScheme("package");
138 mContext.registerReceiver(mBroadcastReceiver, filter);
139 }
140
141 // ----- Track installation/removal of packages -----
142 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
143 public void onReceive(Context context, Intent intent) {
144 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
145
146 Uri uri = intent.getData();
147 if (uri == null) {
148 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700149 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700150 String pkgName = uri.getSchemeSpecificPart();
151 if (pkgName == null) {
152 return;
153 }
154
155 String action = intent.getAction();
156 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
157 synchronized (mBackupParticipants) {
158 Bundle extras = intent.getExtras();
159 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
160 // The package was just upgraded
161 updatePackageParticipantsLocked(pkgName);
162 } else {
163 // The package was just added
164 addPackageParticipantsLocked(pkgName);
165 }
166 }
167 }
168 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
169 Bundle extras = intent.getExtras();
170 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
171 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
172 } else {
173 synchronized (mBackupParticipants) {
174 removePackageParticipantsLocked(pkgName);
175 }
176 }
177 }
178 }
179 };
180
Joe Onorato8ad02812009-05-13 01:41:44 -0400181 // ----- Run the actual backup process asynchronously -----
182
Christopher Tate181fafa2009-05-14 11:12:14 -0700183 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400184 public void handleMessage(Message msg) {
185
186 switch (msg.what) {
187 case MSG_RUN_BACKUP:
188 // snapshot the pending-backup set and work on that
189 synchronized (mQueueLock) {
Joe Onoratod2110db2009-05-19 13:41:21 -0700190 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700191 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700192 for (BackupRequest b: mPendingBackups.values()) {
193 mBackupQueue.add(b);
194 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700195 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400196 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400197 // !!! TODO: start a new backup-queue journal file too
198 // WARNING: If we crash after this line, anything in mPendingBackups will
199 // be lost. FIX THIS.
200 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700201 (new PerformBackupThread(mTransportId, mBackupQueue)).run();
202 break;
203
204 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400205 break;
206 }
207 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400208 }
209
Christopher Tate043dadc2009-06-02 16:11:00 -0700210 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
211 final String packageName = request.appInfo.packageName;
Christopher Tate181fafa2009-05-14 11:12:14 -0700212 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Joe Onorato8ad02812009-05-13 01:41:44 -0400213
Christopher Tate181fafa2009-05-14 11:12:14 -0700214 try {
Christopher Tate7b881282009-06-07 13:52:37 -0700215 // Look up the package info & signatures. This is first so that if it
216 // throws an exception, there's no file setup yet that would need to
217 // be unraveled.
Christopher Tatedf01dea2009-06-09 20:45:02 -0700218 PackageInfo packInfo = mPackageManager.getPackageInfo(packageName,
219 PackageManager.GET_SIGNATURES);
Christopher Tate7b881282009-06-07 13:52:37 -0700220
Christopher Tate043dadc2009-06-02 16:11:00 -0700221 // !!! TODO: get the state file dir from the transport
222 File savedStateName = new File(mStateDir, packageName);
223 File backupDataName = new File(mDataDir, packageName + ".data");
224 File newStateName = new File(mStateDir, packageName + ".new");
Joe Onorato8ad02812009-05-13 01:41:44 -0400225
226 // In a full backup, we pass a null ParcelFileDescriptor as
227 // the saved-state "file"
228 ParcelFileDescriptor savedState = (request.fullBackup) ? null
229 : ParcelFileDescriptor.open(savedStateName,
230 ParcelFileDescriptor.MODE_READ_ONLY |
231 ParcelFileDescriptor.MODE_CREATE);
232
233 backupDataName.delete();
234 ParcelFileDescriptor backupData =
235 ParcelFileDescriptor.open(backupDataName,
236 ParcelFileDescriptor.MODE_READ_WRITE |
237 ParcelFileDescriptor.MODE_CREATE);
238
239 newStateName.delete();
240 ParcelFileDescriptor newState =
241 ParcelFileDescriptor.open(newStateName,
242 ParcelFileDescriptor.MODE_READ_WRITE |
243 ParcelFileDescriptor.MODE_CREATE);
244
245 // Run the target's backup pass
Christopher Tate043dadc2009-06-02 16:11:00 -0700246 boolean success = false;
Joe Onorato8ad02812009-05-13 01:41:44 -0400247 try {
Christopher Tate043dadc2009-06-02 16:11:00 -0700248 agent.doBackup(savedState, backupData, newState);
249 success = true;
Joe Onorato8ad02812009-05-13 01:41:44 -0400250 } finally {
251 if (savedState != null) {
252 savedState.close();
253 }
254 backupData.close();
255 newState.close();
256 }
257
Christopher Tate043dadc2009-06-02 16:11:00 -0700258 // Now propagate the newly-backed-up data to the transport
259 if (success) {
Christopher Tate1885b372009-06-04 15:00:33 -0700260 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
Christopher Tate043dadc2009-06-02 16:11:00 -0700261 backupData =
262 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate7b881282009-06-07 13:52:37 -0700263 int error = transport.performBackup(packInfo, backupData);
Christopher Tate043dadc2009-06-02 16:11:00 -0700264
265 // !!! TODO: After successful transport, delete the now-stale data
266 // and juggle the files so that next time the new state is passed
267 //backupDataName.delete();
268 newStateName.renameTo(savedStateName);
269 }
Christopher Tate7b881282009-06-07 13:52:37 -0700270 } catch (NameNotFoundException e) {
271 Log.e(TAG, "Package not found on backup: " + packageName);
Joe Onorato8ad02812009-05-13 01:41:44 -0400272 } catch (FileNotFoundException fnf) {
Christopher Tate7b881282009-06-07 13:52:37 -0700273 Log.w(TAG, "File not found on backup: ");
Joe Onorato8ad02812009-05-13 01:41:44 -0400274 fnf.printStackTrace();
275 } catch (RemoteException e) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700276 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
Joe Onorato8ad02812009-05-13 01:41:44 -0400277 e.printStackTrace();
278 } catch (Exception e) {
279 Log.w(TAG, "Final exception guard in backup: ");
280 e.printStackTrace();
281 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400282 }
283
Christopher Tate181fafa2009-05-14 11:12:14 -0700284 // Add the backup agents in the given package to our set of known backup participants.
285 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700286 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700287 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700288 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700289 List<ApplicationInfo> targetApps = allAgentApps();
290 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700291 }
292
Christopher Tate181fafa2009-05-14 11:12:14 -0700293 private void addPackageParticipantsLockedInner(String packageName,
294 List<ApplicationInfo> targetApps) {
295 if (DEBUG) {
296 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
297 for (ApplicationInfo a : targetApps) {
298 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
299 }
300 }
301
302 for (ApplicationInfo app : targetApps) {
303 if (packageName == null || app.packageName.equals(packageName)) {
304 int uid = app.uid;
305 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700306 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700307 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700308 mBackupParticipants.put(uid, set);
309 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700310 set.add(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700311 }
Christopher Tate487529a2009-04-29 14:03:25 -0700312 }
313 }
314
Christopher Tate3799bc22009-05-06 16:13:56 -0700315 // Remove the given package's backup services from our known active set. If
316 // 'packageName' is null, *all* backup services will be removed.
317 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700318 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700319 List<ApplicationInfo> allApps = null;
320 if (packageName != null) {
321 allApps = new ArrayList<ApplicationInfo>();
322 try {
323 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
324 allApps.add(app);
325 } catch (Exception e) {
326 // just skip it
327 }
328 } else {
329 // all apps with agents
330 allApps = allAgentApps();
331 }
332 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700333 }
334
Joe Onorato8ad02812009-05-13 01:41:44 -0400335 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700336 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700337 if (DEBUG) {
338 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
339 + ") removing " + agents.size() + " entries");
340 for (ApplicationInfo a : agents) {
341 Log.v(TAG, " - " + a);
342 }
343 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700344 for (ApplicationInfo app : agents) {
345 if (packageName == null || app.packageName.equals(packageName)) {
346 int uid = app.uid;
347 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700348 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700349 // Find the existing entry with the same package name, and remove it.
350 // We can't just remove(app) because the instances are different.
351 for (ApplicationInfo entry: set) {
352 if (entry.packageName.equals(app.packageName)) {
353 set.remove(entry);
354 break;
355 }
356 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700357 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700358 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700359 }
360 }
361 }
362 }
363
Christopher Tate181fafa2009-05-14 11:12:14 -0700364 // Returns the set of all applications that define an android:backupAgent attribute
365 private List<ApplicationInfo> allAgentApps() {
366 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
367 int N = allApps.size();
368 if (N > 0) {
369 for (int a = N-1; a >= 0; a--) {
370 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700371 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
372 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700373 allApps.remove(a);
374 }
375 }
376 }
377 return allApps;
378 }
379
Christopher Tate3799bc22009-05-06 16:13:56 -0700380 // Reset the given package's known backup participants. Unlike add/remove, the update
381 // action cannot be passed a null package name.
382 void updatePackageParticipantsLocked(String packageName) {
383 if (packageName == null) {
384 Log.e(TAG, "updatePackageParticipants called with null package name");
385 return;
386 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700387 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700388
389 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700390 List<ApplicationInfo> allApps = allAgentApps();
391 removePackageParticipantsLockedInner(packageName, allApps);
392 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700393 }
394
Christopher Tate8c850b72009-06-07 19:33:20 -0700395 // Instantiate the given transport
396 private IBackupTransport createTransport(int transportID) {
397 IBackupTransport transport = null;
398 switch (transportID) {
399 case BackupManager.TRANSPORT_ADB:
400 if (DEBUG) Log.v(TAG, "Initializing adb transport");
401 transport = new AdbTransport();
402 break;
403
404 case BackupManager.TRANSPORT_GOOGLE:
405 if (DEBUG) Log.v(TAG, "Initializing Google transport");
406 //!!! TODO: stand up the google backup transport for real here
407 transport = new GoogleTransport();
408 break;
409
410 default:
411 Log.e(TAG, "creating unknown transport " + transportID);
412 }
413 return transport;
414 }
415
Christopher Tatedf01dea2009-06-09 20:45:02 -0700416 // fire off a backup agent, blocking until it attaches or times out
417 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
418 IBackupAgent agent = null;
419 synchronized(mAgentConnectLock) {
420 mConnecting = true;
421 mConnectedAgent = null;
422 try {
423 if (mActivityManager.bindBackupAgent(app, mode)) {
424 Log.d(TAG, "awaiting agent for " + app);
425
426 // success; wait for the agent to arrive
427 while (mConnecting && mConnectedAgent == null) {
428 try {
429 mAgentConnectLock.wait(10000);
430 } catch (InterruptedException e) {
431 // just retry
432 return null;
433 }
434 }
435
436 // if we timed out with no connect, abort and move on
437 if (mConnecting == true) {
438 Log.w(TAG, "Timeout waiting for agent " + app);
439 return null;
440 }
441 agent = mConnectedAgent;
442 }
443 } catch (RemoteException e) {
444 // can't happen
445 }
446 }
447 return agent;
448 }
449
Christopher Tate043dadc2009-06-02 16:11:00 -0700450 // ----- Back up a set of applications via a worker thread -----
451
452 class PerformBackupThread extends Thread {
453 private static final String TAG = "PerformBackupThread";
454 int mTransport;
455 ArrayList<BackupRequest> mQueue;
456
457 public PerformBackupThread(int transportId, ArrayList<BackupRequest> queue) {
458 mTransport = transportId;
459 mQueue = queue;
460 }
461
462 @Override
463 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700464 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
465
466 // stand up the current transport
Christopher Tate8c850b72009-06-07 19:33:20 -0700467 IBackupTransport transport = createTransport(mTransport);
468 if (transport == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700469 return;
470 }
471
Christopher Tatedf01dea2009-06-09 20:45:02 -0700472 // start up the transport
473 try {
474 transport.startSession();
475 } catch (Exception e) {
476 Log.e(TAG, "Error session transport");
477 e.printStackTrace();
478 return;
479 }
480
Christopher Tate043dadc2009-06-02 16:11:00 -0700481 // The transport is up and running; now run all the backups in our queue
482 doQueuedBackups(transport);
483
484 // Finally, tear down the transport
485 try {
486 transport.endSession();
487 } catch (Exception e) {
488 Log.e(TAG, "Error ending transport");
489 e.printStackTrace();
490 }
491 }
492
493 private void doQueuedBackups(IBackupTransport transport) {
494 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700495 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700496
497 IBackupAgent agent = null;
498 int mode = (request.fullBackup)
499 ? IApplicationThread.BACKUP_MODE_FULL
500 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
501 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700502 agent = bindToAgentSynchronous(request.appInfo, mode);
503 if (agent != null) {
504 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700505 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700506
507 // unbind even on timeout, just in case
508 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700509 } catch (SecurityException ex) {
510 // Try for the next one.
511 Log.d(TAG, "error in bind", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700512 } catch (RemoteException e) {
513 // can't happen
514 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700515
Christopher Tate043dadc2009-06-02 16:11:00 -0700516 }
517 }
518 }
519
Christopher Tatedf01dea2009-06-09 20:45:02 -0700520
521 // ----- Restore handling -----
522
523 // Is the given package restorable on this device? Returns the on-device app's
524 // ApplicationInfo struct if it is; null if not.
525 //
526 // !!! TODO: also consider signatures
527 ApplicationInfo isRestorable(PackageInfo packageInfo) {
528 if (packageInfo.packageName != null) {
529 try {
530 ApplicationInfo app = mPackageManager.getApplicationInfo(packageInfo.packageName,
531 PackageManager.GET_SIGNATURES);
532 if ((app.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
533 return app;
534 }
535 } catch (Exception e) {
536 // doesn't exist on this device, or other error -- just ignore it.
537 }
538 }
539 return null;
540 }
541
542 class PerformRestoreThread extends Thread {
543 private IBackupTransport mTransport;
544
545 PerformRestoreThread(IBackupTransport transport) {
546 mTransport = transport;
547 }
548
549 @Override
550 public void run() {
551 /**
552 * Restore sequence:
553 *
554 * 1. start up the transport session
555 * 2. get the restore set description for our identity
556 * 3. for each app in the restore set:
557 * 3.a. if it's restorable on this device, add it to the restore queue
558 * 4. for each app in the restore queue:
559 * 4.b. get the restore data for the app from the transport
560 * 4.c. launch the backup agent for the app
561 * 4.d. agent.doRestore() with the data from the server
562 * 4.e. unbind the agent [and kill the app?]
563 * 5. shut down the transport
564 */
565
566 int err = -1;
567 try {
568 err = mTransport.startSession();
569 } catch (Exception e) {
570 Log.e(TAG, "Error starting transport for restore");
571 e.printStackTrace();
572 }
573
574 if (err == 0) {
575 // build the set of apps to restore
576 try {
577 RestoreSet[] images = mTransport.getAvailableRestoreSets();
578 if (images.length > 0) {
579 // !!! for now we always take the first set
580 RestoreSet image = images[0];
581
582 // build the set of apps we will attempt to restore
583 PackageInfo[] packages = mTransport.getAppSet(image.token);
584 HashSet<ApplicationInfo> appsToRestore = new HashSet<ApplicationInfo>();
585 for (PackageInfo pkg: packages) {
586 ApplicationInfo app = isRestorable(pkg);
587 if (app != null) {
588 appsToRestore.add(app);
589 }
590 }
591
592 // now run the restore queue
593 doQueuedRestores(appsToRestore);
594 }
595 } catch (RemoteException e) {
596 // can't happen; transports run locally
597 }
598
599 // done; shut down the transport
600 try {
601 mTransport.endSession();
602 } catch (Exception e) {
603 Log.e(TAG, "Error ending transport for restore");
604 e.printStackTrace();
605 }
606 }
607
608 // even if the initial session startup failed, report that we're done here
609 }
610
611 // restore each app in the queue
612 void doQueuedRestores(HashSet<ApplicationInfo> appsToRestore) {
613 for (ApplicationInfo app : appsToRestore) {
614 Log.d(TAG, "starting agent for restore of " + app);
615
616 IBackupAgent agent = null;
617 try {
618 agent = bindToAgentSynchronous(app, IApplicationThread.BACKUP_MODE_RESTORE);
619 if (agent != null) {
620 processOneRestore(app, agent);
621 }
622
623 // unbind even on timeout, just in case
624 mActivityManager.unbindBackupAgent(app);
625 } catch (SecurityException ex) {
626 // Try for the next one.
627 Log.d(TAG, "error in bind", ex);
628 } catch (RemoteException e) {
629 // can't happen
630 }
631
632 }
633 }
634
635 // do the guts of a restore
636 void processOneRestore(ApplicationInfo app, IBackupAgent agent) {
637 // !!! TODO: actually run the restore through mTransport
638 }
639 }
640
641
Christopher Tate487529a2009-04-29 14:03:25 -0700642 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700643
Christopher Tatea8bf8152009-04-30 11:36:21 -0700644 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700645 // Record that we need a backup pass for the caller. Since multiple callers
646 // may share a uid, we need to note all candidates within that uid and schedule
647 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700648
649 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700650
Christopher Tate181fafa2009-05-14 11:12:14 -0700651 HashSet<ApplicationInfo> targets = mBackupParticipants.get(Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -0700652 if (targets != null) {
653 synchronized (mQueueLock) {
654 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -0700655 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -0700656 // validate the caller-supplied package name against the known set of
657 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -0700658 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -0400659 // Add the caller to the set of pending backups. If there is
660 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -0700661 BackupRequest req = new BackupRequest(app, false);
662 mPendingBackups.put(app, req);
Joe Onorato8ad02812009-05-13 01:41:44 -0400663 // !!! TODO: write to the pending-backup journal file in case of crash
Christopher Tate487529a2009-04-29 14:03:25 -0700664 }
665 }
666
Christopher Tate181fafa2009-05-14 11:12:14 -0700667 if (DEBUG) {
668 int numKeys = mPendingBackups.size();
669 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
670 for (BackupRequest b : mPendingBackups.values()) {
671 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
672 }
673 }
Christopher Tate487529a2009-04-29 14:03:25 -0700674 // Schedule a backup pass in a few minutes. As backup-eligible data
675 // keeps changing, continue to defer the backup pass until things
676 // settle down, to avoid extra overhead.
Christopher Tate043dadc2009-06-02 16:11:00 -0700677 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate487529a2009-04-29 14:03:25 -0700678 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
679 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700680 } else {
681 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700682 }
683 }
Christopher Tate46758122009-05-06 11:22:00 -0700684
Christopher Tate043dadc2009-06-02 16:11:00 -0700685 // Schedule a backup pass for a given package. This method will schedule a
686 // full backup even for apps that do not declare an android:backupAgent, so
687 // use with care.
Christopher Tate46758122009-05-06 11:22:00 -0700688 public void scheduleFullBackup(String packageName) throws RemoteException {
Christopher Tate043dadc2009-06-02 16:11:00 -0700689 mContext.enforceCallingPermission("android.permission.BACKUP", "scheduleFullBackup");
690
691 if (DEBUG) Log.v(TAG, "Scheduling immediate full backup for " + packageName);
Christopher Tate46758122009-05-06 11:22:00 -0700692 synchronized (mQueueLock) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700693 try {
694 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
695 mPendingBackups.put(app, new BackupRequest(app, true));
696 mBackupHandler.sendEmptyMessage(MSG_RUN_FULL_BACKUP);
697 } catch (NameNotFoundException e) {
698 Log.w(TAG, "Could not find app for " + packageName + " to schedule full backup");
Christopher Tate46758122009-05-06 11:22:00 -0700699 }
700 }
701 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700702
Christopher Tate043dadc2009-06-02 16:11:00 -0700703 // Select which transport to use for the next backup operation
704 public int selectBackupTransport(int transportId) {
705 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
706
707 int prevTransport = mTransportId;
708 mTransportId = transportId;
709 return prevTransport;
710 }
711
712 // Callback: a requested backup agent has been instantiated. This should only
713 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700714 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700715 synchronized(mAgentConnectLock) {
716 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
717 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
718 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
719 mConnectedAgent = agent;
720 mConnecting = false;
721 } else {
722 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
723 + " claiming agent connected");
724 }
725 mAgentConnectLock.notifyAll();
726 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700727 }
728
729 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
730 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -0700731 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700732 public void agentDisconnected(String packageName) {
733 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -0700734 synchronized(mAgentConnectLock) {
735 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
736 mConnectedAgent = null;
737 mConnecting = false;
738 } else {
739 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
740 + " claiming agent disconnected");
741 }
742 mAgentConnectLock.notifyAll();
743 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700744 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700745
Christopher Tate8c850b72009-06-07 19:33:20 -0700746 // Hand off a restore session
747 public IRestoreSession beginRestoreSession(int transportID) {
748 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
749 return null;
750 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700751
Christopher Tate9b3905c2009-06-08 15:24:01 -0700752 // ----- Restore session -----
753
754 class RestoreSession extends IRestoreSession.Stub {
755 private IBackupTransport mRestoreTransport = null;
756 RestoreSet[] mRestoreSets = null;
757
758 RestoreSession(int transportID) {
759 mRestoreTransport = createTransport(transportID);
760 }
761
762 // --- Binder interface ---
763 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
764 synchronized(this) {
765 if (mRestoreSets == null) {
766 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
767 }
768 return mRestoreSets;
769 }
770 }
771
772 public int performRestore(int token) throws android.os.RemoteException {
773 return -1;
774 }
775
776 public void endRestoreSession() throws android.os.RemoteException {
777 mRestoreTransport.endSession();
778 mRestoreTransport = null;
779 }
780 }
781
Christopher Tate043dadc2009-06-02 16:11:00 -0700782
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700783 @Override
784 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
785 synchronized (mQueueLock) {
786 int N = mBackupParticipants.size();
787 pw.println("Participants:");
788 for (int i=0; i<N; i++) {
789 int uid = mBackupParticipants.keyAt(i);
790 pw.print(" uid: ");
791 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700792 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
793 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700794 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -0700795 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700796 }
797 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700798 pw.println("Pending:");
799 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
800 while (br.hasNext()) {
801 pw.print(" ");
802 pw.println(br);
803 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700804 }
805 }
Christopher Tate487529a2009-04-29 14:03:25 -0700806}