blob: 0d2590c58e128f0aa17f7fb00d06ce2d88f75984 [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;
71
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;
93
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 Tate043dadc2009-06-02 16:11:00 -0700123 private int mTransportId;
Christopher Tatef68eb502009-06-16 11:02:01 -0700124 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700125
Christopher Tate22b87872009-05-04 16:41:53 -0700126 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700127 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700128 private File mJournalDir;
129 private File mJournal;
130 private RandomAccessFile mJournalStream;
Christopher Tate487529a2009-04-29 14:03:25 -0700131
Christopher Tate487529a2009-04-29 14:03:25 -0700132 public BackupManagerService(Context context) {
133 mContext = context;
134 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700135 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700136
Christopher Tate22b87872009-05-04 16:41:53 -0700137 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700138 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700139 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700140 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700141
Christopher Tatecde87f42009-06-12 12:55:53 -0700142 // Set up the backup-request journaling
143 mJournalDir = new File(mStateDir, "pending");
144 mJournalDir.mkdirs();
145 makeJournalLocked(); // okay because no other threads are running yet
146
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700147 //!!! TODO: default to cloud transport, not local
148 mTransportId = BackupManager.TRANSPORT_LOCAL;
Christopher Tate22b87872009-05-04 16:41:53 -0700149
Christopher Tate3799bc22009-05-06 16:13:56 -0700150 // Build our mapping of uid to backup client services
151 synchronized (mBackupParticipants) {
152 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700153 }
154
Christopher Tatecde87f42009-06-12 12:55:53 -0700155 // Now that we know about valid backup participants, parse any
156 // leftover journal files and schedule a new backup pass
157 parseLeftoverJournals();
158
Christopher Tate3799bc22009-05-06 16:13:56 -0700159 // Register for broadcasts about package install, etc., so we can
160 // update the provider list.
161 IntentFilter filter = new IntentFilter();
162 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
163 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
164 filter.addDataScheme("package");
165 mContext.registerReceiver(mBroadcastReceiver, filter);
166 }
167
Christopher Tatecde87f42009-06-12 12:55:53 -0700168 private void makeJournalLocked() {
169 try {
170 mJournal = File.createTempFile("journal", null, mJournalDir);
171 mJournalStream = new RandomAccessFile(mJournal, "rwd");
172 } catch (IOException e) {
173 Log.e(TAG, "Unable to write backup journals");
174 mJournal = null;
175 mJournalStream = null;
176 }
177 }
178
179 private void parseLeftoverJournals() {
180 if (mJournal != null) {
181 File[] allJournals = mJournalDir.listFiles();
182 for (File f : allJournals) {
183 if (f.compareTo(mJournal) != 0) {
184 // This isn't the current journal, so it must be a leftover. Read
185 // out the package names mentioned there and schedule them for
186 // backup.
187 try {
188 Log.i(TAG, "Found stale backup journal, scheduling:");
189 RandomAccessFile in = new RandomAccessFile(f, "r");
190 while (true) {
191 String packageName = in.readUTF();
192 Log.i(TAG, " + " + packageName);
193 dataChanged(packageName);
194 }
195 } catch (EOFException e) {
196 // no more data; we're done
197 } catch (Exception e) {
198 // can't read it or other error; just skip it
199 } finally {
200 // close/delete the file
201 f.delete();
202 }
203 }
204 }
205 }
206 }
207
Christopher Tate3799bc22009-05-06 16:13:56 -0700208 // ----- Track installation/removal of packages -----
209 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
210 public void onReceive(Context context, Intent intent) {
211 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
212
213 Uri uri = intent.getData();
214 if (uri == null) {
215 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700216 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700217 String pkgName = uri.getSchemeSpecificPart();
218 if (pkgName == null) {
219 return;
220 }
221
222 String action = intent.getAction();
223 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
224 synchronized (mBackupParticipants) {
225 Bundle extras = intent.getExtras();
226 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
227 // The package was just upgraded
228 updatePackageParticipantsLocked(pkgName);
229 } else {
230 // The package was just added
231 addPackageParticipantsLocked(pkgName);
232 }
233 }
234 }
235 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
236 Bundle extras = intent.getExtras();
237 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
238 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
239 } else {
240 synchronized (mBackupParticipants) {
241 removePackageParticipantsLocked(pkgName);
242 }
243 }
244 }
245 }
246 };
247
Joe Onorato8ad02812009-05-13 01:41:44 -0400248 // ----- Run the actual backup process asynchronously -----
249
Christopher Tate181fafa2009-05-14 11:12:14 -0700250 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400251 public void handleMessage(Message msg) {
252
253 switch (msg.what) {
254 case MSG_RUN_BACKUP:
255 // snapshot the pending-backup set and work on that
Christopher Tatecde87f42009-06-12 12:55:53 -0700256 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400257 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700258 if (mPendingBackups.size() == 0) {
259 Log.v(TAG, "Backup requested but nothing pending");
260 break;
261 }
262
Joe Onoratod2110db2009-05-19 13:41:21 -0700263 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700264 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700265 for (BackupRequest b: mPendingBackups.values()) {
266 mBackupQueue.add(b);
267 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700268 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400269 }
Christopher Tateace7f092009-06-15 18:07:25 -0700270
271 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700272 if (mJournalStream != null) {
273 try {
274 mJournalStream.close();
275 } catch (IOException e) {
276 // don't need to do anything
277 }
278 makeJournalLocked();
279 }
280
281 // At this point, we have started a new journal file, and the old
282 // file identity is being passed to the backup processing thread.
283 // When it completes successfully, that old journal file will be
284 // deleted. If we crash prior to that, the old journal is parsed
285 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400286 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700287 (new PerformBackupThread(mTransportId, mBackupQueue, oldJournal)).run();
Christopher Tate043dadc2009-06-02 16:11:00 -0700288 break;
289
290 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400291 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700292
293 case MSG_RUN_RESTORE:
294 {
295 int token = msg.arg1;
296 IBackupTransport transport = (IBackupTransport)msg.obj;
297 (new PerformRestoreThread(transport, token)).run();
298 break;
299 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400300 }
301 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400302 }
303
Christopher Tate181fafa2009-05-14 11:12:14 -0700304 // Add the backup agents in the given package to our set of known backup participants.
305 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700306 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700307 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700308 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700309 List<ApplicationInfo> targetApps = allAgentApps();
310 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700311 }
312
Christopher Tate181fafa2009-05-14 11:12:14 -0700313 private void addPackageParticipantsLockedInner(String packageName,
314 List<ApplicationInfo> targetApps) {
315 if (DEBUG) {
316 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
317 for (ApplicationInfo a : targetApps) {
318 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
319 }
320 }
321
322 for (ApplicationInfo app : targetApps) {
323 if (packageName == null || app.packageName.equals(packageName)) {
324 int uid = app.uid;
325 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700326 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700327 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700328 mBackupParticipants.put(uid, set);
329 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700330 set.add(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700331 }
Christopher Tate487529a2009-04-29 14:03:25 -0700332 }
333 }
334
Christopher Tate3799bc22009-05-06 16:13:56 -0700335 // Remove the given package's backup services from our known active set. If
336 // 'packageName' is null, *all* backup services will be removed.
337 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700338 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700339 List<ApplicationInfo> allApps = null;
340 if (packageName != null) {
341 allApps = new ArrayList<ApplicationInfo>();
342 try {
343 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
344 allApps.add(app);
345 } catch (Exception e) {
346 // just skip it
347 }
348 } else {
349 // all apps with agents
350 allApps = allAgentApps();
351 }
352 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700353 }
354
Joe Onorato8ad02812009-05-13 01:41:44 -0400355 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700356 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700357 if (DEBUG) {
358 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
359 + ") removing " + agents.size() + " entries");
360 for (ApplicationInfo a : agents) {
361 Log.v(TAG, " - " + a);
362 }
363 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700364 for (ApplicationInfo app : agents) {
365 if (packageName == null || app.packageName.equals(packageName)) {
366 int uid = app.uid;
367 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700368 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700369 // Find the existing entry with the same package name, and remove it.
370 // We can't just remove(app) because the instances are different.
371 for (ApplicationInfo entry: set) {
372 if (entry.packageName.equals(app.packageName)) {
373 set.remove(entry);
374 break;
375 }
376 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700377 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700378 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700379 }
380 }
381 }
382 }
383
Christopher Tate181fafa2009-05-14 11:12:14 -0700384 // Returns the set of all applications that define an android:backupAgent attribute
385 private List<ApplicationInfo> allAgentApps() {
386 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
387 int N = allApps.size();
388 if (N > 0) {
389 for (int a = N-1; a >= 0; a--) {
390 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700391 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
392 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700393 allApps.remove(a);
394 }
395 }
396 }
397 return allApps;
398 }
399
Christopher Tate3799bc22009-05-06 16:13:56 -0700400 // Reset the given package's known backup participants. Unlike add/remove, the update
401 // action cannot be passed a null package name.
402 void updatePackageParticipantsLocked(String packageName) {
403 if (packageName == null) {
404 Log.e(TAG, "updatePackageParticipants called with null package name");
405 return;
406 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700407 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700408
409 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700410 List<ApplicationInfo> allApps = allAgentApps();
411 removePackageParticipantsLockedInner(packageName, allApps);
412 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700413 }
414
Christopher Tate8c850b72009-06-07 19:33:20 -0700415 // Instantiate the given transport
416 private IBackupTransport createTransport(int transportID) {
417 IBackupTransport transport = null;
418 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700419 case BackupManager.TRANSPORT_LOCAL:
420 if (DEBUG) Log.v(TAG, "Initializing local transport");
421 transport = new LocalTransport(mContext);
Christopher Tate8c850b72009-06-07 19:33:20 -0700422 break;
423
424 case BackupManager.TRANSPORT_GOOGLE:
425 if (DEBUG) Log.v(TAG, "Initializing Google transport");
426 //!!! TODO: stand up the google backup transport for real here
427 transport = new GoogleTransport();
428 break;
429
430 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700431 Log.e(TAG, "Asked for unknown transport " + transportID);
Christopher Tate8c850b72009-06-07 19:33:20 -0700432 }
433 return transport;
434 }
435
Christopher Tatedf01dea2009-06-09 20:45:02 -0700436 // fire off a backup agent, blocking until it attaches or times out
437 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
438 IBackupAgent agent = null;
439 synchronized(mAgentConnectLock) {
440 mConnecting = true;
441 mConnectedAgent = null;
442 try {
443 if (mActivityManager.bindBackupAgent(app, mode)) {
444 Log.d(TAG, "awaiting agent for " + app);
445
446 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700447 // only wait 10 seconds for the clear data to happen
448 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
449 while (mConnecting && mConnectedAgent == null
450 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700451 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700452 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700453 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700454 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700455 return null;
456 }
457 }
458
459 // if we timed out with no connect, abort and move on
460 if (mConnecting == true) {
461 Log.w(TAG, "Timeout waiting for agent " + app);
462 return null;
463 }
464 agent = mConnectedAgent;
465 }
466 } catch (RemoteException e) {
467 // can't happen
468 }
469 }
470 return agent;
471 }
472
Christopher Tatec7b31e32009-06-10 15:49:30 -0700473 // clear an application's data, blocking until the operation completes or times out
474 void clearApplicationDataSynchronous(String packageName) {
475 ClearDataObserver observer = new ClearDataObserver();
476
477 synchronized(mClearDataLock) {
478 mClearingData = true;
479 mPackageManager.clearApplicationUserData(packageName, observer);
480
481 // only wait 10 seconds for the clear data to happen
482 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
483 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
484 try {
485 mClearDataLock.wait(5000);
486 } catch (InterruptedException e) {
487 // won't happen, but still.
488 mClearingData = false;
489 }
490 }
491 }
492 }
493
494 class ClearDataObserver extends IPackageDataObserver.Stub {
495 public void onRemoveCompleted(String packageName, boolean succeeded)
496 throws android.os.RemoteException {
497 synchronized(mClearDataLock) {
498 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700499 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700500 }
501 }
502 }
503
Christopher Tate043dadc2009-06-02 16:11:00 -0700504 // ----- Back up a set of applications via a worker thread -----
505
506 class PerformBackupThread extends Thread {
507 private static final String TAG = "PerformBackupThread";
508 int mTransport;
509 ArrayList<BackupRequest> mQueue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700510 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700511
Christopher Tatecde87f42009-06-12 12:55:53 -0700512 public PerformBackupThread(int transportId, ArrayList<BackupRequest> queue,
513 File journal) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700514 mTransport = transportId;
515 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700516 mJournal = journal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700517 }
518
519 @Override
520 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700521 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
522
523 // stand up the current transport
Christopher Tate8c850b72009-06-07 19:33:20 -0700524 IBackupTransport transport = createTransport(mTransport);
525 if (transport == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700526 return;
527 }
528
Christopher Tatedf01dea2009-06-09 20:45:02 -0700529 // start up the transport
530 try {
531 transport.startSession();
532 } catch (Exception e) {
533 Log.e(TAG, "Error session transport");
534 e.printStackTrace();
535 return;
536 }
537
Christopher Tate043dadc2009-06-02 16:11:00 -0700538 // The transport is up and running; now run all the backups in our queue
539 doQueuedBackups(transport);
540
541 // Finally, tear down the transport
542 try {
543 transport.endSession();
544 } catch (Exception e) {
545 Log.e(TAG, "Error ending transport");
546 e.printStackTrace();
547 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700548
549 if (!mJournal.delete()) {
550 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
551 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700552 }
553
554 private void doQueuedBackups(IBackupTransport transport) {
555 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700556 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700557
558 IBackupAgent agent = null;
559 int mode = (request.fullBackup)
560 ? IApplicationThread.BACKUP_MODE_FULL
561 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
562 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700563 agent = bindToAgentSynchronous(request.appInfo, mode);
564 if (agent != null) {
565 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700566 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700567
568 // unbind even on timeout, just in case
569 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700570 } catch (SecurityException ex) {
571 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700572 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700573 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700574 Log.v(TAG, "bind/backup threw");
575 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700576 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700577
Christopher Tate043dadc2009-06-02 16:11:00 -0700578 }
579 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700580
581 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
582 final String packageName = request.appInfo.packageName;
583 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
584
585 try {
586 // Look up the package info & signatures. This is first so that if it
587 // throws an exception, there's no file setup yet that would need to
588 // be unraveled.
589 PackageInfo packInfo = mPackageManager.getPackageInfo(packageName,
590 PackageManager.GET_SIGNATURES);
591
592 // !!! TODO: get the state file dir from the transport
593 File savedStateName = new File(mStateDir, packageName);
594 File backupDataName = new File(mDataDir, packageName + ".data");
595 File newStateName = new File(mStateDir, packageName + ".new");
596
597 // In a full backup, we pass a null ParcelFileDescriptor as
598 // the saved-state "file"
599 ParcelFileDescriptor savedState = (request.fullBackup) ? null
600 : ParcelFileDescriptor.open(savedStateName,
601 ParcelFileDescriptor.MODE_READ_ONLY |
602 ParcelFileDescriptor.MODE_CREATE);
603
604 backupDataName.delete();
605 ParcelFileDescriptor backupData =
606 ParcelFileDescriptor.open(backupDataName,
607 ParcelFileDescriptor.MODE_READ_WRITE |
608 ParcelFileDescriptor.MODE_CREATE);
609
610 newStateName.delete();
611 ParcelFileDescriptor newState =
612 ParcelFileDescriptor.open(newStateName,
613 ParcelFileDescriptor.MODE_READ_WRITE |
614 ParcelFileDescriptor.MODE_CREATE);
615
616 // Run the target's backup pass
617 boolean success = false;
618 try {
619 agent.doBackup(savedState, backupData, newState);
620 success = true;
621 } finally {
622 if (savedState != null) {
623 savedState.close();
624 }
625 backupData.close();
626 newState.close();
627 }
628
629 // Now propagate the newly-backed-up data to the transport
630 if (success) {
631 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
632 backupData =
633 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
634 int error = transport.performBackup(packInfo, backupData);
635
636 // !!! TODO: After successful transport, delete the now-stale data
637 // and juggle the files so that next time the new state is passed
638 //backupDataName.delete();
639 newStateName.renameTo(savedStateName);
640 }
641 } catch (NameNotFoundException e) {
642 Log.e(TAG, "Package not found on backup: " + packageName);
643 } catch (FileNotFoundException fnf) {
644 Log.w(TAG, "File not found on backup: ");
645 fnf.printStackTrace();
646 } catch (RemoteException e) {
647 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
648 e.printStackTrace();
649 } catch (Exception e) {
650 Log.w(TAG, "Final exception guard in backup: ");
651 e.printStackTrace();
652 }
653 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700654 }
655
Christopher Tatedf01dea2009-06-09 20:45:02 -0700656
657 // ----- Restore handling -----
658
659 // Is the given package restorable on this device? Returns the on-device app's
660 // ApplicationInfo struct if it is; null if not.
661 //
662 // !!! TODO: also consider signatures
Christopher Tatec7b31e32009-06-10 15:49:30 -0700663 PackageInfo isRestorable(PackageInfo packageInfo) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700664 if (packageInfo.packageName != null) {
665 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700666 PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
Christopher Tatedf01dea2009-06-09 20:45:02 -0700667 PackageManager.GET_SIGNATURES);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700668 if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700669 return app;
670 }
671 } catch (Exception e) {
672 // doesn't exist on this device, or other error -- just ignore it.
673 }
674 }
675 return null;
676 }
677
678 class PerformRestoreThread extends Thread {
679 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700680 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700681 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700682
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700683 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700684 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700685 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700686 }
687
688 @Override
689 public void run() {
690 /**
691 * Restore sequence:
692 *
693 * 1. start up the transport session
694 * 2. get the restore set description for our identity
695 * 3. for each app in the restore set:
696 * 3.a. if it's restorable on this device, add it to the restore queue
697 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700698 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700699 * 4.b. get the restore data for the app from the transport
700 * 4.c. launch the backup agent for the app
701 * 4.d. agent.doRestore() with the data from the server
702 * 4.e. unbind the agent [and kill the app?]
703 * 5. shut down the transport
704 */
705
706 int err = -1;
707 try {
708 err = mTransport.startSession();
709 } catch (Exception e) {
710 Log.e(TAG, "Error starting transport for restore");
711 e.printStackTrace();
712 }
713
714 if (err == 0) {
715 // build the set of apps to restore
716 try {
717 RestoreSet[] images = mTransport.getAvailableRestoreSets();
718 if (images.length > 0) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700719 // !!! TODO: pick out the set for this token
Christopher Tatec7b31e32009-06-10 15:49:30 -0700720 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700721
722 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700723 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
724 HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700725 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700726 // get the real PackageManager idea of the package
727 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700728 if (app != null) {
729 appsToRestore.add(app);
730 }
731 }
732
733 // now run the restore queue
734 doQueuedRestores(appsToRestore);
735 }
736 } catch (RemoteException e) {
737 // can't happen; transports run locally
738 }
739
740 // done; shut down the transport
741 try {
742 mTransport.endSession();
743 } catch (Exception e) {
744 Log.e(TAG, "Error ending transport for restore");
745 e.printStackTrace();
746 }
747 }
748
749 // even if the initial session startup failed, report that we're done here
750 }
751
752 // restore each app in the queue
Christopher Tatec7b31e32009-06-10 15:49:30 -0700753 void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
754 for (PackageInfo app : appsToRestore) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700755 Log.d(TAG, "starting agent for restore of " + app);
756
Christopher Tatedf01dea2009-06-09 20:45:02 -0700757 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700758 // Remove the app's data first
759 clearApplicationDataSynchronous(app.packageName);
760
761 // Now perform the restore into the clean app
762 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
763 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700764 if (agent != null) {
765 processOneRestore(app, agent);
766 }
767
768 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700769 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700770 } catch (SecurityException ex) {
771 // Try for the next one.
772 Log.d(TAG, "error in bind", ex);
773 } catch (RemoteException e) {
774 // can't happen
775 }
776
777 }
778 }
779
Christopher Tatec7b31e32009-06-10 15:49:30 -0700780 // Do the guts of a restore of one application, derived from the 'mImage'
781 // restore set via the 'mTransport' transport.
782 void processOneRestore(PackageInfo app, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700783 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700784 final String packageName = app.packageName;
785
786 // !!! TODO: get the dirs from the transport
787 File backupDataName = new File(mDataDir, packageName + ".restore");
788 backupDataName.delete();
789 try {
790 ParcelFileDescriptor backupData =
791 ParcelFileDescriptor.open(backupDataName,
792 ParcelFileDescriptor.MODE_READ_WRITE |
793 ParcelFileDescriptor.MODE_CREATE);
794
795 // Run the transport's restore pass
796 // Run the target's backup pass
797 int err = -1;
798 try {
799 err = mTransport.getRestoreData(mImage.token, app, backupData);
800 } catch (RemoteException e) {
801 // can't happen
802 } finally {
803 backupData.close();
804 }
805
806 // Okay, we have the data. Now have the agent do the restore.
807 File newStateName = new File(mStateDir, packageName + ".new");
808 ParcelFileDescriptor newState =
809 ParcelFileDescriptor.open(newStateName,
810 ParcelFileDescriptor.MODE_READ_WRITE |
811 ParcelFileDescriptor.MODE_CREATE);
812
813 backupData = ParcelFileDescriptor.open(backupDataName,
814 ParcelFileDescriptor.MODE_READ_ONLY);
815
816 boolean success = false;
817 try {
818 agent.doRestore(backupData, newState);
819 success = true;
820 } catch (Exception e) {
821 Log.e(TAG, "Restore failed for " + packageName);
822 e.printStackTrace();
823 } finally {
824 newState.close();
825 backupData.close();
826 }
827
828 // if everything went okay, remember the recorded state now
829 if (success) {
830 File savedStateName = new File(mStateDir, packageName);
831 newStateName.renameTo(savedStateName);
832 }
833 } catch (FileNotFoundException fnfe) {
834 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
835 } catch (IOException ioe) {
836 Log.e(TAG, "Unable to process restore file: " + ioe);
837 } catch (Exception e) {
838 Log.e(TAG, "Final exception guard in restore:");
839 e.printStackTrace();
840 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700841 }
842 }
843
844
Christopher Tate487529a2009-04-29 14:03:25 -0700845 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700846
Christopher Tatea8bf8152009-04-30 11:36:21 -0700847 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700848 // Record that we need a backup pass for the caller. Since multiple callers
849 // may share a uid, we need to note all candidates within that uid and schedule
850 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700851
852 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700853
854 // If the caller does not hold the BACKUP permission, it can only request a
855 // backup of its own data.
856 HashSet<ApplicationInfo> targets;
857 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
858 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
859 targets = mBackupParticipants.get(Binder.getCallingUid());
860 } else {
861 // a caller with full permission can ask to back up any participating app
862 // !!! TODO: allow backup of ANY app?
863 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
864 targets = new HashSet<ApplicationInfo>();
865 int N = mBackupParticipants.size();
866 for (int i = 0; i < N; i++) {
867 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
868 if (s != null) {
869 targets.addAll(s);
870 }
871 }
872 }
Christopher Tate487529a2009-04-29 14:03:25 -0700873 if (targets != null) {
874 synchronized (mQueueLock) {
875 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -0700876 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -0700877 // validate the caller-supplied package name against the known set of
878 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -0700879 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -0400880 // Add the caller to the set of pending backups. If there is
881 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -0700882 BackupRequest req = new BackupRequest(app, false);
883 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -0700884
885 // Journal this request in case of crash
886 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700887 }
888 }
889
Christopher Tate181fafa2009-05-14 11:12:14 -0700890 if (DEBUG) {
891 int numKeys = mPendingBackups.size();
892 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
893 for (BackupRequest b : mPendingBackups.values()) {
894 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
895 }
896 }
Christopher Tate487529a2009-04-29 14:03:25 -0700897 // Schedule a backup pass in a few minutes. As backup-eligible data
898 // keeps changing, continue to defer the backup pass until things
899 // settle down, to avoid extra overhead.
Christopher Tate043dadc2009-06-02 16:11:00 -0700900 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate487529a2009-04-29 14:03:25 -0700901 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
902 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700903 } else {
904 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700905 }
906 }
Christopher Tate46758122009-05-06 11:22:00 -0700907
Christopher Tatecde87f42009-06-12 12:55:53 -0700908 private void writeToJournalLocked(String str) {
909 if (mJournalStream != null) {
910 try {
911 mJournalStream.writeUTF(str);
912 } catch (IOException e) {
913 Log.e(TAG, "Error writing to backup journal");
914 mJournalStream = null;
915 mJournal = null;
916 }
917 }
918 }
919
Christopher Tateace7f092009-06-15 18:07:25 -0700920 // Run a backup pass immediately for any applications that have declared
921 // that they have pending updates.
922 public void backupNow() throws RemoteException {
923 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -0700924
Christopher Tateace7f092009-06-15 18:07:25 -0700925 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -0700926 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700927 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
928 mBackupHandler.sendEmptyMessage(MSG_RUN_BACKUP);
Christopher Tate46758122009-05-06 11:22:00 -0700929 }
930 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700931
Christopher Tateace7f092009-06-15 18:07:25 -0700932 // Report the currently active transport
933 public int getCurrentTransport() {
934 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
935 return mTransportId;
936 }
937
Christopher Tate043dadc2009-06-02 16:11:00 -0700938 // Select which transport to use for the next backup operation
939 public int selectBackupTransport(int transportId) {
940 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
941
942 int prevTransport = mTransportId;
943 mTransportId = transportId;
944 return prevTransport;
945 }
946
947 // Callback: a requested backup agent has been instantiated. This should only
948 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700949 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700950 synchronized(mAgentConnectLock) {
951 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
952 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
953 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
954 mConnectedAgent = agent;
955 mConnecting = false;
956 } else {
957 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
958 + " claiming agent connected");
959 }
960 mAgentConnectLock.notifyAll();
961 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700962 }
963
964 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
965 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -0700966 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700967 public void agentDisconnected(String packageName) {
968 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -0700969 synchronized(mAgentConnectLock) {
970 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
971 mConnectedAgent = null;
972 mConnecting = false;
973 } else {
974 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
975 + " claiming agent disconnected");
976 }
977 mAgentConnectLock.notifyAll();
978 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700979 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700980
Christopher Tate8c850b72009-06-07 19:33:20 -0700981 // Hand off a restore session
982 public IRestoreSession beginRestoreSession(int transportID) {
983 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -0700984
985 synchronized(this) {
986 if (mActiveRestoreSession != null) {
987 Log.d(TAG, "Restore session requested but one already active");
988 return null;
989 }
990 mActiveRestoreSession = new RestoreSession(transportID);
991 }
992 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -0700993 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700994
Christopher Tate9b3905c2009-06-08 15:24:01 -0700995 // ----- Restore session -----
996
997 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -0700998 private static final String TAG = "RestoreSession";
999
Christopher Tate9b3905c2009-06-08 15:24:01 -07001000 private IBackupTransport mRestoreTransport = null;
1001 RestoreSet[] mRestoreSets = null;
1002
1003 RestoreSession(int transportID) {
1004 mRestoreTransport = createTransport(transportID);
1005 }
1006
1007 // --- Binder interface ---
1008 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001009 mContext.enforceCallingPermission("android.permission.BACKUP",
1010 "getAvailableRestoreSets");
1011
Christopher Tatef68eb502009-06-16 11:02:01 -07001012 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001013 synchronized(this) {
1014 if (mRestoreSets == null) {
1015 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1016 }
1017 return mRestoreSets;
1018 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001019 } catch (RuntimeException e) {
1020 Log.d(TAG, "getAvailableRestoreSets exception");
1021 e.printStackTrace();
1022 throw e;
1023 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001024 }
1025
1026 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001027 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1028
1029 if (mRestoreSets != null) {
1030 for (int i = 0; i < mRestoreSets.length; i++) {
1031 if (token == mRestoreSets[i].token) {
1032 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1033 mRestoreTransport);
1034 msg.arg1 = token;
1035 mBackupHandler.sendMessage(msg);
1036 return 0;
1037 }
1038 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001039 } else {
1040 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001041 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001042 return -1;
1043 }
1044
1045 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001046 mContext.enforceCallingPermission("android.permission.BACKUP",
1047 "endRestoreSession");
1048
Christopher Tate9b3905c2009-06-08 15:24:01 -07001049 mRestoreTransport.endSession();
1050 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001051 synchronized(BackupManagerService.this) {
1052 if (BackupManagerService.this.mActiveRestoreSession == this) {
1053 BackupManagerService.this.mActiveRestoreSession = null;
1054 } else {
1055 Log.e(TAG, "ending non-current restore session");
1056 }
1057 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001058 }
1059 }
1060
Christopher Tate043dadc2009-06-02 16:11:00 -07001061
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001062 @Override
1063 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1064 synchronized (mQueueLock) {
1065 int N = mBackupParticipants.size();
1066 pw.println("Participants:");
1067 for (int i=0; i<N; i++) {
1068 int uid = mBackupParticipants.keyAt(i);
1069 pw.print(" uid: ");
1070 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001071 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1072 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001073 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001074 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001075 }
1076 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001077 pw.println("Pending:");
1078 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
1079 while (br.hasNext()) {
1080 pw.print(" ");
1081 pw.println(br);
1082 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001083 }
1084 }
Christopher Tate487529a2009-04-29 14:03:25 -07001085}