blob: d842d341fa3538e2254f61e491f003edf6fede59 [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
Christopher Tate9bbc21a2009-06-10 20:23:25 -070050import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070051import com.android.internal.backup.GoogleTransport;
52import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070053
Christopher Tatecde87f42009-06-12 12:55:53 -070054import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070055import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070056import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070057import java.io.FileNotFoundException;
Christopher Tatec7b31e32009-06-10 15:49:30 -070058import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070059import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070060import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070061import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040062import java.util.ArrayList;
63import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070064import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070065import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070066import java.util.List;
67
68class BackupManagerService extends IBackupManager.Stub {
69 private static final String TAG = "BackupManagerService";
70 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070071
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070072 private static final long COLLECTION_INTERVAL = 1000;
73 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070074
75 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070076 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070077 private static final int MSG_RUN_RESTORE = 3;
Christopher Tatec7b31e32009-06-10 15:49:30 -070078
79 // Timeout interval for deciding that a bind or clear-data has taken too long
80 static final long TIMEOUT_INTERVAL = 10 * 1000;
81
Christopher Tate487529a2009-04-29 14:03:25 -070082 private Context mContext;
83 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070084 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070085 private final BackupHandler mBackupHandler = new BackupHandler();
86 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070087 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
88 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070089 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070090 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070091 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070092 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -070093
Christopher Tate181fafa2009-05-14 11:12:14 -070094 BackupRequest(ApplicationInfo app, boolean isFull) {
95 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -070096 fullBackup = isFull;
97 }
Christopher Tate181fafa2009-05-14 11:12:14 -070098
99 public String toString() {
100 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
101 }
Christopher Tate46758122009-05-06 11:22:00 -0700102 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400103 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700104 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
105 = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400106 // Backups that we have started. These are separate to prevent starvation
107 // if an app keeps re-enqueuing itself.
108 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -0700109 private final Object mQueueLock = new Object();
110
Christopher Tate043dadc2009-06-02 16:11:00 -0700111 // The thread performing the sequence of queued backups binds to each app's agent
112 // in succession. Bind notifications are asynchronously delivered through the
113 // Activity Manager; use this lock object to signal when a requested binding has
114 // completed.
115 private final Object mAgentConnectLock = new Object();
116 private IBackupAgent mConnectedAgent;
117 private volatile boolean mConnecting;
118
Christopher Tatec7b31e32009-06-10 15:49:30 -0700119 // A similar synchronicity mechanism around clearing apps' data for restore
120 private final Object mClearDataLock = new Object();
121 private volatile boolean mClearingData;
122
Christopher Tateaa088442009-06-16 18:25:46 -0700123 // Current active transport & restore session
Christopher Tate043dadc2009-06-02 16:11:00 -0700124 private int mTransportId;
Christopher Tateaa088442009-06-16 18:25:46 -0700125 private IBackupTransport mTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700126 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700127
Christopher Tate22b87872009-05-04 16:41:53 -0700128 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700129 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700130 private File mJournalDir;
131 private File mJournal;
132 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700133
Christopher Tate487529a2009-04-29 14:03:25 -0700134 public BackupManagerService(Context context) {
135 mContext = context;
136 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700137 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700138
Christopher Tate22b87872009-05-04 16:41:53 -0700139 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700140 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700141 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700142 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700143
Christopher Tatecde87f42009-06-12 12:55:53 -0700144 // Set up the backup-request journaling
145 mJournalDir = new File(mStateDir, "pending");
146 mJournalDir.mkdirs();
147 makeJournalLocked(); // okay because no other threads are running yet
148
Christopher Tate3799bc22009-05-06 16:13:56 -0700149 // Build our mapping of uid to backup client services
150 synchronized (mBackupParticipants) {
151 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700152 }
153
Christopher Tateaa088442009-06-16 18:25:46 -0700154 // Stand up our default transport
155 //!!! TODO: default to cloud transport, not local
156 mTransportId = BackupManager.TRANSPORT_LOCAL;
157 mTransport = createTransport(mTransportId);
158
Christopher Tatecde87f42009-06-12 12:55:53 -0700159 // Now that we know about valid backup participants, parse any
160 // leftover journal files and schedule a new backup pass
161 parseLeftoverJournals();
162
Christopher Tate3799bc22009-05-06 16:13:56 -0700163 // Register for broadcasts about package install, etc., so we can
164 // update the provider list.
165 IntentFilter filter = new IntentFilter();
166 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
167 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
168 filter.addDataScheme("package");
169 mContext.registerReceiver(mBroadcastReceiver, filter);
170 }
171
Christopher Tatecde87f42009-06-12 12:55:53 -0700172 private void makeJournalLocked() {
173 try {
174 mJournal = File.createTempFile("journal", null, mJournalDir);
175 mJournalStream = new RandomAccessFile(mJournal, "rwd");
176 } catch (IOException e) {
177 Log.e(TAG, "Unable to write backup journals");
178 mJournal = null;
179 mJournalStream = null;
180 }
181 }
182
183 private void parseLeftoverJournals() {
184 if (mJournal != null) {
185 File[] allJournals = mJournalDir.listFiles();
186 for (File f : allJournals) {
187 if (f.compareTo(mJournal) != 0) {
188 // This isn't the current journal, so it must be a leftover. Read
189 // out the package names mentioned there and schedule them for
190 // backup.
191 try {
192 Log.i(TAG, "Found stale backup journal, scheduling:");
193 RandomAccessFile in = new RandomAccessFile(f, "r");
194 while (true) {
195 String packageName = in.readUTF();
196 Log.i(TAG, " + " + packageName);
197 dataChanged(packageName);
198 }
199 } catch (EOFException e) {
200 // no more data; we're done
201 } catch (Exception e) {
202 // can't read it or other error; just skip it
203 } finally {
204 // close/delete the file
205 f.delete();
206 }
207 }
208 }
209 }
210 }
211
Christopher Tate3799bc22009-05-06 16:13:56 -0700212 // ----- Track installation/removal of packages -----
213 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
214 public void onReceive(Context context, Intent intent) {
215 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
216
217 Uri uri = intent.getData();
218 if (uri == null) {
219 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700220 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700221 String pkgName = uri.getSchemeSpecificPart();
222 if (pkgName == null) {
223 return;
224 }
225
226 String action = intent.getAction();
227 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
228 synchronized (mBackupParticipants) {
229 Bundle extras = intent.getExtras();
230 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
231 // The package was just upgraded
232 updatePackageParticipantsLocked(pkgName);
233 } else {
234 // The package was just added
235 addPackageParticipantsLocked(pkgName);
236 }
237 }
238 }
239 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
240 Bundle extras = intent.getExtras();
241 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
242 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
243 } else {
244 synchronized (mBackupParticipants) {
245 removePackageParticipantsLocked(pkgName);
246 }
247 }
248 }
249 }
250 };
251
Joe Onorato8ad02812009-05-13 01:41:44 -0400252 // ----- Run the actual backup process asynchronously -----
253
Christopher Tate181fafa2009-05-14 11:12:14 -0700254 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400255 public void handleMessage(Message msg) {
256
257 switch (msg.what) {
258 case MSG_RUN_BACKUP:
259 // snapshot the pending-backup set and work on that
Christopher Tatecde87f42009-06-12 12:55:53 -0700260 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400261 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700262 if (mPendingBackups.size() == 0) {
263 Log.v(TAG, "Backup requested but nothing pending");
264 break;
265 }
266
Joe Onoratod2110db2009-05-19 13:41:21 -0700267 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700268 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700269 for (BackupRequest b: mPendingBackups.values()) {
270 mBackupQueue.add(b);
271 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700272 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400273 }
Christopher Tateace7f092009-06-15 18:07:25 -0700274
275 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700276 if (mJournalStream != null) {
277 try {
278 mJournalStream.close();
279 } catch (IOException e) {
280 // don't need to do anything
281 }
282 makeJournalLocked();
283 }
284
285 // At this point, we have started a new journal file, and the old
286 // file identity is being passed to the backup processing thread.
287 // When it completes successfully, that old journal file will be
288 // deleted. If we crash prior to that, the old journal is parsed
289 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400290 }
Christopher Tateaa088442009-06-16 18:25:46 -0700291 (new PerformBackupThread(mTransport, mBackupQueue, oldJournal)).run();
Christopher Tate043dadc2009-06-02 16:11:00 -0700292 break;
293
294 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400295 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700296
297 case MSG_RUN_RESTORE:
298 {
299 int token = msg.arg1;
300 IBackupTransport transport = (IBackupTransport)msg.obj;
301 (new PerformRestoreThread(transport, token)).run();
302 break;
303 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400304 }
305 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400306 }
307
Christopher Tate181fafa2009-05-14 11:12:14 -0700308 // Add the backup agents in the given package to our set of known backup participants.
309 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700310 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700311 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700312 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700313 List<ApplicationInfo> targetApps = allAgentApps();
314 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700315 }
316
Christopher Tate181fafa2009-05-14 11:12:14 -0700317 private void addPackageParticipantsLockedInner(String packageName,
318 List<ApplicationInfo> targetApps) {
319 if (DEBUG) {
320 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
321 for (ApplicationInfo a : targetApps) {
322 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
323 }
324 }
325
326 for (ApplicationInfo app : targetApps) {
327 if (packageName == null || app.packageName.equals(packageName)) {
328 int uid = app.uid;
329 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700330 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700331 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700332 mBackupParticipants.put(uid, set);
333 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700334 set.add(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700335 }
Christopher Tate487529a2009-04-29 14:03:25 -0700336 }
337 }
338
Christopher Tate3799bc22009-05-06 16:13:56 -0700339 // Remove the given package's backup services from our known active set. If
340 // 'packageName' is null, *all* backup services will be removed.
341 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700342 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700343 List<ApplicationInfo> allApps = null;
344 if (packageName != null) {
345 allApps = new ArrayList<ApplicationInfo>();
346 try {
347 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
348 allApps.add(app);
349 } catch (Exception e) {
350 // just skip it
351 }
352 } else {
353 // all apps with agents
354 allApps = allAgentApps();
355 }
356 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700357 }
358
Joe Onorato8ad02812009-05-13 01:41:44 -0400359 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700360 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700361 if (DEBUG) {
362 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
363 + ") removing " + agents.size() + " entries");
364 for (ApplicationInfo a : agents) {
365 Log.v(TAG, " - " + a);
366 }
367 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700368 for (ApplicationInfo app : agents) {
369 if (packageName == null || app.packageName.equals(packageName)) {
370 int uid = app.uid;
371 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700372 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700373 // Find the existing entry with the same package name, and remove it.
374 // We can't just remove(app) because the instances are different.
375 for (ApplicationInfo entry: set) {
376 if (entry.packageName.equals(app.packageName)) {
377 set.remove(entry);
378 break;
379 }
380 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700381 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700382 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700383 }
384 }
385 }
386 }
387
Christopher Tate181fafa2009-05-14 11:12:14 -0700388 // Returns the set of all applications that define an android:backupAgent attribute
389 private List<ApplicationInfo> allAgentApps() {
390 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
391 int N = allApps.size();
392 if (N > 0) {
393 for (int a = N-1; a >= 0; a--) {
394 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700395 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
396 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700397 allApps.remove(a);
398 }
399 }
400 }
401 return allApps;
402 }
Christopher Tateaa088442009-06-16 18:25:46 -0700403
Christopher Tate3799bc22009-05-06 16:13:56 -0700404 // Reset the given package's known backup participants. Unlike add/remove, the update
405 // action cannot be passed a null package name.
406 void updatePackageParticipantsLocked(String packageName) {
407 if (packageName == null) {
408 Log.e(TAG, "updatePackageParticipants called with null package name");
409 return;
410 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700411 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700412
413 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700414 List<ApplicationInfo> allApps = allAgentApps();
415 removePackageParticipantsLockedInner(packageName, allApps);
416 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700417 }
418
Christopher Tate8c850b72009-06-07 19:33:20 -0700419 // Instantiate the given transport
420 private IBackupTransport createTransport(int transportID) {
421 IBackupTransport transport = null;
422 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700423 case BackupManager.TRANSPORT_LOCAL:
424 if (DEBUG) Log.v(TAG, "Initializing local transport");
425 transport = new LocalTransport(mContext);
Christopher Tate8c850b72009-06-07 19:33:20 -0700426 break;
427
428 case BackupManager.TRANSPORT_GOOGLE:
429 if (DEBUG) Log.v(TAG, "Initializing Google transport");
430 //!!! TODO: stand up the google backup transport for real here
431 transport = new GoogleTransport();
432 break;
433
434 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700435 Log.e(TAG, "Asked for unknown transport " + transportID);
Christopher Tate8c850b72009-06-07 19:33:20 -0700436 }
437 return transport;
438 }
439
Christopher Tatedf01dea2009-06-09 20:45:02 -0700440 // fire off a backup agent, blocking until it attaches or times out
441 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
442 IBackupAgent agent = null;
443 synchronized(mAgentConnectLock) {
444 mConnecting = true;
445 mConnectedAgent = null;
446 try {
447 if (mActivityManager.bindBackupAgent(app, mode)) {
448 Log.d(TAG, "awaiting agent for " + app);
449
450 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700451 // only wait 10 seconds for the clear data to happen
452 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
453 while (mConnecting && mConnectedAgent == null
454 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700455 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700456 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700457 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700458 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700459 return null;
460 }
461 }
462
463 // if we timed out with no connect, abort and move on
464 if (mConnecting == true) {
465 Log.w(TAG, "Timeout waiting for agent " + app);
466 return null;
467 }
468 agent = mConnectedAgent;
469 }
470 } catch (RemoteException e) {
471 // can't happen
472 }
473 }
474 return agent;
475 }
476
Christopher Tatec7b31e32009-06-10 15:49:30 -0700477 // clear an application's data, blocking until the operation completes or times out
478 void clearApplicationDataSynchronous(String packageName) {
479 ClearDataObserver observer = new ClearDataObserver();
480
481 synchronized(mClearDataLock) {
482 mClearingData = true;
483 mPackageManager.clearApplicationUserData(packageName, observer);
484
485 // only wait 10 seconds for the clear data to happen
486 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
487 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
488 try {
489 mClearDataLock.wait(5000);
490 } catch (InterruptedException e) {
491 // won't happen, but still.
492 mClearingData = false;
493 }
494 }
495 }
496 }
497
498 class ClearDataObserver extends IPackageDataObserver.Stub {
499 public void onRemoveCompleted(String packageName, boolean succeeded)
500 throws android.os.RemoteException {
501 synchronized(mClearDataLock) {
502 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700503 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700504 }
505 }
506 }
507
Christopher Tate043dadc2009-06-02 16:11:00 -0700508 // ----- Back up a set of applications via a worker thread -----
509
510 class PerformBackupThread extends Thread {
511 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700512 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700513 ArrayList<BackupRequest> mQueue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700514 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700515
Christopher Tateaa088442009-06-16 18:25:46 -0700516 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700517 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700518 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700519 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700520 mJournal = journal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700521 }
522
523 @Override
524 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700525 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
526
Christopher Tatedf01dea2009-06-09 20:45:02 -0700527 // start up the transport
528 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700529 mTransport.startSession();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700530 } catch (Exception e) {
531 Log.e(TAG, "Error session transport");
532 e.printStackTrace();
533 return;
534 }
535
Christopher Tate043dadc2009-06-02 16:11:00 -0700536 // The transport is up and running; now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700537 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700538
539 // Finally, tear down the transport
540 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700541 mTransport.endSession();
Christopher Tate043dadc2009-06-02 16:11:00 -0700542 } catch (Exception e) {
543 Log.e(TAG, "Error ending transport");
544 e.printStackTrace();
545 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700546
547 if (!mJournal.delete()) {
548 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
549 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700550 }
551
552 private void doQueuedBackups(IBackupTransport transport) {
553 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700554 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700555
556 IBackupAgent agent = null;
557 int mode = (request.fullBackup)
558 ? IApplicationThread.BACKUP_MODE_FULL
559 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
560 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700561 agent = bindToAgentSynchronous(request.appInfo, mode);
562 if (agent != null) {
563 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700564 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700565
566 // unbind even on timeout, just in case
567 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700568 } catch (SecurityException ex) {
569 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700570 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700571 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700572 Log.v(TAG, "bind/backup threw");
573 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700574 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700575
Christopher Tate043dadc2009-06-02 16:11:00 -0700576 }
577 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700578
579 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
580 final String packageName = request.appInfo.packageName;
581 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
582
583 try {
584 // Look up the package info & signatures. This is first so that if it
585 // throws an exception, there's no file setup yet that would need to
586 // be unraveled.
587 PackageInfo packInfo = mPackageManager.getPackageInfo(packageName,
588 PackageManager.GET_SIGNATURES);
589
590 // !!! TODO: get the state file dir from the transport
591 File savedStateName = new File(mStateDir, packageName);
592 File backupDataName = new File(mDataDir, packageName + ".data");
593 File newStateName = new File(mStateDir, packageName + ".new");
594
595 // In a full backup, we pass a null ParcelFileDescriptor as
596 // the saved-state "file"
597 ParcelFileDescriptor savedState = (request.fullBackup) ? null
598 : ParcelFileDescriptor.open(savedStateName,
599 ParcelFileDescriptor.MODE_READ_ONLY |
600 ParcelFileDescriptor.MODE_CREATE);
601
602 backupDataName.delete();
603 ParcelFileDescriptor backupData =
604 ParcelFileDescriptor.open(backupDataName,
605 ParcelFileDescriptor.MODE_READ_WRITE |
606 ParcelFileDescriptor.MODE_CREATE);
607
608 newStateName.delete();
609 ParcelFileDescriptor newState =
610 ParcelFileDescriptor.open(newStateName,
611 ParcelFileDescriptor.MODE_READ_WRITE |
612 ParcelFileDescriptor.MODE_CREATE);
613
614 // Run the target's backup pass
615 boolean success = false;
616 try {
617 agent.doBackup(savedState, backupData, newState);
618 success = true;
619 } finally {
620 if (savedState != null) {
621 savedState.close();
622 }
623 backupData.close();
624 newState.close();
625 }
626
627 // Now propagate the newly-backed-up data to the transport
628 if (success) {
629 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
630 backupData =
631 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
632 int error = transport.performBackup(packInfo, backupData);
633
634 // !!! TODO: After successful transport, delete the now-stale data
635 // and juggle the files so that next time the new state is passed
636 //backupDataName.delete();
637 newStateName.renameTo(savedStateName);
638 }
639 } catch (NameNotFoundException e) {
640 Log.e(TAG, "Package not found on backup: " + packageName);
641 } catch (FileNotFoundException fnf) {
642 Log.w(TAG, "File not found on backup: ");
643 fnf.printStackTrace();
644 } catch (RemoteException e) {
645 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
646 e.printStackTrace();
647 } catch (Exception e) {
648 Log.w(TAG, "Final exception guard in backup: ");
649 e.printStackTrace();
650 }
651 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700652 }
653
Christopher Tatedf01dea2009-06-09 20:45:02 -0700654
655 // ----- Restore handling -----
656
657 // Is the given package restorable on this device? Returns the on-device app's
658 // ApplicationInfo struct if it is; null if not.
659 //
660 // !!! TODO: also consider signatures
Christopher Tatec7b31e32009-06-10 15:49:30 -0700661 PackageInfo isRestorable(PackageInfo packageInfo) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700662 if (packageInfo.packageName != null) {
663 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700664 PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
Christopher Tatedf01dea2009-06-09 20:45:02 -0700665 PackageManager.GET_SIGNATURES);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700666 if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700667 return app;
668 }
669 } catch (Exception e) {
670 // doesn't exist on this device, or other error -- just ignore it.
671 }
672 }
673 return null;
674 }
675
676 class PerformRestoreThread extends Thread {
677 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700678 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700679 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700680
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700681 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700682 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700683 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700684 }
685
686 @Override
687 public void run() {
688 /**
689 * Restore sequence:
690 *
691 * 1. start up the transport session
692 * 2. get the restore set description for our identity
693 * 3. for each app in the restore set:
694 * 3.a. if it's restorable on this device, add it to the restore queue
695 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700696 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700697 * 4.b. get the restore data for the app from the transport
698 * 4.c. launch the backup agent for the app
699 * 4.d. agent.doRestore() with the data from the server
700 * 4.e. unbind the agent [and kill the app?]
701 * 5. shut down the transport
702 */
703
704 int err = -1;
705 try {
706 err = mTransport.startSession();
707 } catch (Exception e) {
708 Log.e(TAG, "Error starting transport for restore");
709 e.printStackTrace();
710 }
711
712 if (err == 0) {
713 // build the set of apps to restore
714 try {
715 RestoreSet[] images = mTransport.getAvailableRestoreSets();
716 if (images.length > 0) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700717 // !!! TODO: pick out the set for this token
Christopher Tatec7b31e32009-06-10 15:49:30 -0700718 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700719
720 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700721 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
722 HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700723 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700724 // get the real PackageManager idea of the package
725 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700726 if (app != null) {
727 appsToRestore.add(app);
728 }
729 }
730
731 // now run the restore queue
732 doQueuedRestores(appsToRestore);
733 }
734 } catch (RemoteException e) {
735 // can't happen; transports run locally
736 }
737
738 // done; shut down the transport
739 try {
740 mTransport.endSession();
741 } catch (Exception e) {
742 Log.e(TAG, "Error ending transport for restore");
743 e.printStackTrace();
744 }
745 }
746
747 // even if the initial session startup failed, report that we're done here
748 }
749
750 // restore each app in the queue
Christopher Tatec7b31e32009-06-10 15:49:30 -0700751 void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
752 for (PackageInfo app : appsToRestore) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700753 Log.d(TAG, "starting agent for restore of " + app);
754
Christopher Tatedf01dea2009-06-09 20:45:02 -0700755 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700756 // Remove the app's data first
757 clearApplicationDataSynchronous(app.packageName);
758
759 // Now perform the restore into the clean app
760 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
761 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700762 if (agent != null) {
763 processOneRestore(app, agent);
764 }
765
766 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700767 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700768 } catch (SecurityException ex) {
769 // Try for the next one.
770 Log.d(TAG, "error in bind", ex);
771 } catch (RemoteException e) {
772 // can't happen
773 }
774
775 }
776 }
777
Christopher Tatec7b31e32009-06-10 15:49:30 -0700778 // Do the guts of a restore of one application, derived from the 'mImage'
779 // restore set via the 'mTransport' transport.
780 void processOneRestore(PackageInfo app, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700781 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700782 final String packageName = app.packageName;
783
784 // !!! TODO: get the dirs from the transport
785 File backupDataName = new File(mDataDir, packageName + ".restore");
786 backupDataName.delete();
787 try {
788 ParcelFileDescriptor backupData =
789 ParcelFileDescriptor.open(backupDataName,
790 ParcelFileDescriptor.MODE_READ_WRITE |
791 ParcelFileDescriptor.MODE_CREATE);
792
793 // Run the transport's restore pass
794 // Run the target's backup pass
795 int err = -1;
796 try {
797 err = mTransport.getRestoreData(mImage.token, app, backupData);
798 } catch (RemoteException e) {
799 // can't happen
800 } finally {
801 backupData.close();
802 }
803
804 // Okay, we have the data. Now have the agent do the restore.
805 File newStateName = new File(mStateDir, packageName + ".new");
806 ParcelFileDescriptor newState =
807 ParcelFileDescriptor.open(newStateName,
808 ParcelFileDescriptor.MODE_READ_WRITE |
809 ParcelFileDescriptor.MODE_CREATE);
810
811 backupData = ParcelFileDescriptor.open(backupDataName,
812 ParcelFileDescriptor.MODE_READ_ONLY);
813
814 boolean success = false;
815 try {
816 agent.doRestore(backupData, newState);
817 success = true;
818 } catch (Exception e) {
819 Log.e(TAG, "Restore failed for " + packageName);
820 e.printStackTrace();
821 } finally {
822 newState.close();
823 backupData.close();
824 }
825
826 // if everything went okay, remember the recorded state now
827 if (success) {
828 File savedStateName = new File(mStateDir, packageName);
829 newStateName.renameTo(savedStateName);
830 }
831 } catch (FileNotFoundException fnfe) {
832 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
833 } catch (IOException ioe) {
834 Log.e(TAG, "Unable to process restore file: " + ioe);
835 } catch (Exception e) {
836 Log.e(TAG, "Final exception guard in restore:");
837 e.printStackTrace();
838 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700839 }
840 }
841
842
Christopher Tate487529a2009-04-29 14:03:25 -0700843 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700844
Christopher Tatea8bf8152009-04-30 11:36:21 -0700845 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700846 // Record that we need a backup pass for the caller. Since multiple callers
847 // may share a uid, we need to note all candidates within that uid and schedule
848 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700849
850 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700851
852 // If the caller does not hold the BACKUP permission, it can only request a
853 // backup of its own data.
854 HashSet<ApplicationInfo> targets;
855 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
856 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
857 targets = mBackupParticipants.get(Binder.getCallingUid());
858 } else {
859 // a caller with full permission can ask to back up any participating app
860 // !!! TODO: allow backup of ANY app?
861 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
862 targets = new HashSet<ApplicationInfo>();
863 int N = mBackupParticipants.size();
864 for (int i = 0; i < N; i++) {
865 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
866 if (s != null) {
867 targets.addAll(s);
868 }
869 }
870 }
Christopher Tate487529a2009-04-29 14:03:25 -0700871 if (targets != null) {
872 synchronized (mQueueLock) {
873 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -0700874 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -0700875 // validate the caller-supplied package name against the known set of
876 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -0700877 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -0400878 // Add the caller to the set of pending backups. If there is
879 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -0700880 BackupRequest req = new BackupRequest(app, false);
881 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -0700882
883 // Journal this request in case of crash
884 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700885 }
886 }
887
Christopher Tate181fafa2009-05-14 11:12:14 -0700888 if (DEBUG) {
889 int numKeys = mPendingBackups.size();
890 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
891 for (BackupRequest b : mPendingBackups.values()) {
892 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
893 }
894 }
Christopher Tate487529a2009-04-29 14:03:25 -0700895 // Schedule a backup pass in a few minutes. As backup-eligible data
896 // keeps changing, continue to defer the backup pass until things
897 // settle down, to avoid extra overhead.
Christopher Tate043dadc2009-06-02 16:11:00 -0700898 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate487529a2009-04-29 14:03:25 -0700899 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
900 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700901 } else {
902 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700903 }
904 }
Christopher Tate46758122009-05-06 11:22:00 -0700905
Christopher Tatecde87f42009-06-12 12:55:53 -0700906 private void writeToJournalLocked(String str) {
907 if (mJournalStream != null) {
908 try {
909 mJournalStream.writeUTF(str);
910 } catch (IOException e) {
911 Log.e(TAG, "Error writing to backup journal");
912 mJournalStream = null;
913 mJournal = null;
914 }
915 }
916 }
917
Christopher Tateace7f092009-06-15 18:07:25 -0700918 // Run a backup pass immediately for any applications that have declared
919 // that they have pending updates.
920 public void backupNow() throws RemoteException {
921 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -0700922
Christopher Tateace7f092009-06-15 18:07:25 -0700923 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -0700924 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700925 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
926 mBackupHandler.sendEmptyMessage(MSG_RUN_BACKUP);
Christopher Tate46758122009-05-06 11:22:00 -0700927 }
928 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700929
Christopher Tateace7f092009-06-15 18:07:25 -0700930 // Report the currently active transport
931 public int getCurrentTransport() {
932 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
933 return mTransportId;
934 }
935
Christopher Tate043dadc2009-06-02 16:11:00 -0700936 // Select which transport to use for the next backup operation
937 public int selectBackupTransport(int transportId) {
938 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
939
Christopher Tateaa088442009-06-16 18:25:46 -0700940 int prevTransport = -1;
941 IBackupTransport newTransport = createTransport(transportId);
942 if (newTransport != null) {
943 // !!! TODO: a method on the old transport that says it's being deactivated?
944 mTransport = newTransport;
945 prevTransport = mTransportId;
946 mTransportId = transportId;
947 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700948 return prevTransport;
949 }
950
951 // Callback: a requested backup agent has been instantiated. This should only
952 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700953 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700954 synchronized(mAgentConnectLock) {
955 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
956 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
957 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
958 mConnectedAgent = agent;
959 mConnecting = false;
960 } else {
961 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
962 + " claiming agent connected");
963 }
964 mAgentConnectLock.notifyAll();
965 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700966 }
967
968 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
969 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -0700970 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700971 public void agentDisconnected(String packageName) {
972 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -0700973 synchronized(mAgentConnectLock) {
974 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
975 mConnectedAgent = null;
976 mConnecting = false;
977 } else {
978 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
979 + " claiming agent disconnected");
980 }
981 mAgentConnectLock.notifyAll();
982 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700983 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700984
Christopher Tate8c850b72009-06-07 19:33:20 -0700985 // Hand off a restore session
986 public IRestoreSession beginRestoreSession(int transportID) {
987 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -0700988
989 synchronized(this) {
990 if (mActiveRestoreSession != null) {
991 Log.d(TAG, "Restore session requested but one already active");
992 return null;
993 }
994 mActiveRestoreSession = new RestoreSession(transportID);
995 }
996 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -0700997 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700998
Christopher Tate9b3905c2009-06-08 15:24:01 -0700999 // ----- Restore session -----
1000
1001 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001002 private static final String TAG = "RestoreSession";
1003
Christopher Tate9b3905c2009-06-08 15:24:01 -07001004 private IBackupTransport mRestoreTransport = null;
1005 RestoreSet[] mRestoreSets = null;
1006
1007 RestoreSession(int transportID) {
1008 mRestoreTransport = createTransport(transportID);
1009 }
1010
1011 // --- Binder interface ---
1012 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001013 mContext.enforceCallingPermission("android.permission.BACKUP",
1014 "getAvailableRestoreSets");
1015
Christopher Tatef68eb502009-06-16 11:02:01 -07001016 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001017 synchronized(this) {
1018 if (mRestoreSets == null) {
1019 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1020 }
1021 return mRestoreSets;
1022 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001023 } catch (RuntimeException e) {
1024 Log.d(TAG, "getAvailableRestoreSets exception");
1025 e.printStackTrace();
1026 throw e;
1027 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001028 }
1029
1030 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001031 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1032
1033 if (mRestoreSets != null) {
1034 for (int i = 0; i < mRestoreSets.length; i++) {
1035 if (token == mRestoreSets[i].token) {
1036 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1037 mRestoreTransport);
1038 msg.arg1 = token;
1039 mBackupHandler.sendMessage(msg);
1040 return 0;
1041 }
1042 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001043 } else {
1044 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001045 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001046 return -1;
1047 }
1048
1049 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001050 mContext.enforceCallingPermission("android.permission.BACKUP",
1051 "endRestoreSession");
1052
Christopher Tate9b3905c2009-06-08 15:24:01 -07001053 mRestoreTransport.endSession();
1054 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001055 synchronized(BackupManagerService.this) {
1056 if (BackupManagerService.this.mActiveRestoreSession == this) {
1057 BackupManagerService.this.mActiveRestoreSession = null;
1058 } else {
1059 Log.e(TAG, "ending non-current restore session");
1060 }
1061 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001062 }
1063 }
1064
Christopher Tate043dadc2009-06-02 16:11:00 -07001065
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001066 @Override
1067 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1068 synchronized (mQueueLock) {
1069 int N = mBackupParticipants.size();
1070 pw.println("Participants:");
1071 for (int i=0; i<N; i++) {
1072 int uid = mBackupParticipants.keyAt(i);
1073 pw.print(" uid: ");
1074 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001075 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1076 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001077 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001078 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001079 }
1080 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001081 pw.println("Pending:");
1082 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
1083 while (br.hasNext()) {
1084 pw.print(" ");
1085 pw.println(br);
1086 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001087 }
1088 }
Christopher Tate487529a2009-04-29 14:03:25 -07001089}