blob: f9a6f5ba244a36e4fc580d7a86283106fdfea1b3 [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;
Dan Egnor87a02bc2009-06-17 02:30:10 -070024import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070025import android.content.Context;
26import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070027import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070028import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070029import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070030import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070031import android.content.pm.PackageInfo;
Christopher Tate043dadc2009-06-02 16:11:00 -070032import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070033import android.content.pm.PackageManager;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070035import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070036import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070037import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070038import android.os.Handler;
39import android.os.IBinder;
40import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070041import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070042import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070043import android.os.RemoteException;
44import android.util.Log;
45import android.util.SparseArray;
46
47import android.backup.IBackupManager;
Christopher Tate8c850b72009-06-07 19:33:20 -070048import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070049import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070050import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070051
Christopher Tate9bbc21a2009-06-10 20:23:25 -070052import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070053import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070054
Christopher Tate6785dd82009-06-18 15:58:25 -070055import com.android.server.PackageManagerBackupAgent;
56
Christopher Tatecde87f42009-06-12 12:55:53 -070057import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070058import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070059import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070060import java.io.FileNotFoundException;
Christopher Tatec7b31e32009-06-10 15:49:30 -070061import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070062import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070063import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070064import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040065import java.util.ArrayList;
66import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070067import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070068import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070069import java.util.List;
70
71class BackupManagerService extends IBackupManager.Stub {
72 private static final String TAG = "BackupManagerService";
73 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070074
Christopher Tate6785dd82009-06-18 15:58:25 -070075 // Default time to wait after data changes before we back up the data
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070076 private static final long COLLECTION_INTERVAL = 1000;
77 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070078
79 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070080 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070081 private static final int MSG_RUN_RESTORE = 3;
Christopher Tatec7b31e32009-06-10 15:49:30 -070082
83 // Timeout interval for deciding that a bind or clear-data has taken too long
84 static final long TIMEOUT_INTERVAL = 10 * 1000;
85
Christopher Tate487529a2009-04-29 14:03:25 -070086 private Context mContext;
87 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070088 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070089 private final BackupHandler mBackupHandler = new BackupHandler();
90 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070091 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
92 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070093 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070094 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070095 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070096 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -070097
Christopher Tate181fafa2009-05-14 11:12:14 -070098 BackupRequest(ApplicationInfo app, boolean isFull) {
99 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700100 fullBackup = isFull;
101 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700102
103 public String toString() {
104 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
105 }
Christopher Tate46758122009-05-06 11:22:00 -0700106 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400107 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700108 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
109 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate6785dd82009-06-18 15:58:25 -0700110 // Do we need to back up the package manager metadata on the next pass?
111 private boolean mDoPackageManager;
112 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Joe Onorato8ad02812009-05-13 01:41:44 -0400113 // Backups that we have started. These are separate to prevent starvation
114 // if an app keeps re-enqueuing itself.
115 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -0700116 private final Object mQueueLock = new Object();
117
Christopher Tate043dadc2009-06-02 16:11:00 -0700118 // The thread performing the sequence of queued backups binds to each app's agent
119 // in succession. Bind notifications are asynchronously delivered through the
120 // Activity Manager; use this lock object to signal when a requested binding has
121 // completed.
122 private final Object mAgentConnectLock = new Object();
123 private IBackupAgent mConnectedAgent;
124 private volatile boolean mConnecting;
125
Christopher Tatec7b31e32009-06-10 15:49:30 -0700126 // A similar synchronicity mechanism around clearing apps' data for restore
127 private final Object mClearDataLock = new Object();
128 private volatile boolean mClearingData;
129
Christopher Tateaa088442009-06-16 18:25:46 -0700130 // Current active transport & restore session
Christopher Tate043dadc2009-06-02 16:11:00 -0700131 private int mTransportId;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700132 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700133 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700134
Christopher Tate22b87872009-05-04 16:41:53 -0700135 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700136 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700137 private File mJournalDir;
138 private File mJournal;
139 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700140
Christopher Tate487529a2009-04-29 14:03:25 -0700141 public BackupManagerService(Context context) {
142 mContext = context;
143 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700144 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700145
Christopher Tate22b87872009-05-04 16:41:53 -0700146 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700147 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700148 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700149 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700150
Christopher Tatecde87f42009-06-12 12:55:53 -0700151 // Set up the backup-request journaling
152 mJournalDir = new File(mStateDir, "pending");
153 mJournalDir.mkdirs();
154 makeJournalLocked(); // okay because no other threads are running yet
155
Christopher Tate3799bc22009-05-06 16:13:56 -0700156 // Build our mapping of uid to backup client services
157 synchronized (mBackupParticipants) {
158 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700159 }
160
Dan Egnor87a02bc2009-06-17 02:30:10 -0700161 // Set up our transport options and initialize the default transport
162 // TODO: Have transports register themselves somehow?
163 // TODO: Don't create transports that we don't need to?
164 mTransportId = BackupManager.TRANSPORT_GOOGLE;
165 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
166 mGoogleTransport = null;
167
168 // Attach to the Google backup transport.
169 Intent intent = new Intent().setComponent(new ComponentName(
170 "com.google.android.backup",
171 "com.google.android.backup.BackupTransportService"));
172 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700173
Christopher Tatecde87f42009-06-12 12:55:53 -0700174 // Now that we know about valid backup participants, parse any
175 // leftover journal files and schedule a new backup pass
176 parseLeftoverJournals();
177
Christopher Tate3799bc22009-05-06 16:13:56 -0700178 // Register for broadcasts about package install, etc., so we can
179 // update the provider list.
180 IntentFilter filter = new IntentFilter();
181 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
182 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
183 filter.addDataScheme("package");
184 mContext.registerReceiver(mBroadcastReceiver, filter);
185 }
186
Christopher Tatecde87f42009-06-12 12:55:53 -0700187 private void makeJournalLocked() {
188 try {
189 mJournal = File.createTempFile("journal", null, mJournalDir);
190 mJournalStream = new RandomAccessFile(mJournal, "rwd");
191 } catch (IOException e) {
192 Log.e(TAG, "Unable to write backup journals");
193 mJournal = null;
194 mJournalStream = null;
195 }
196 }
197
198 private void parseLeftoverJournals() {
199 if (mJournal != null) {
200 File[] allJournals = mJournalDir.listFiles();
201 for (File f : allJournals) {
202 if (f.compareTo(mJournal) != 0) {
203 // This isn't the current journal, so it must be a leftover. Read
204 // out the package names mentioned there and schedule them for
205 // backup.
206 try {
207 Log.i(TAG, "Found stale backup journal, scheduling:");
208 RandomAccessFile in = new RandomAccessFile(f, "r");
209 while (true) {
210 String packageName = in.readUTF();
211 Log.i(TAG, " + " + packageName);
212 dataChanged(packageName);
213 }
214 } catch (EOFException e) {
215 // no more data; we're done
216 } catch (Exception e) {
217 // can't read it or other error; just skip it
218 } finally {
219 // close/delete the file
220 f.delete();
221 }
222 }
223 }
224 }
225 }
226
Christopher Tate3799bc22009-05-06 16:13:56 -0700227 // ----- Track installation/removal of packages -----
228 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
229 public void onReceive(Context context, Intent intent) {
230 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
231
232 Uri uri = intent.getData();
233 if (uri == null) {
234 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700235 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700236 String pkgName = uri.getSchemeSpecificPart();
237 if (pkgName == null) {
238 return;
239 }
240
241 String action = intent.getAction();
242 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
243 synchronized (mBackupParticipants) {
244 Bundle extras = intent.getExtras();
245 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
246 // The package was just upgraded
247 updatePackageParticipantsLocked(pkgName);
248 } else {
249 // The package was just added
250 addPackageParticipantsLocked(pkgName);
251 }
252 }
253 }
254 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
255 Bundle extras = intent.getExtras();
256 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
257 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
258 } else {
259 synchronized (mBackupParticipants) {
260 removePackageParticipantsLocked(pkgName);
261 }
262 }
263 }
264 }
265 };
266
Dan Egnor87a02bc2009-06-17 02:30:10 -0700267 // ----- Track connection to GoogleBackupTransport service -----
268 ServiceConnection mGoogleConnection = new ServiceConnection() {
269 public void onServiceConnected(ComponentName name, IBinder service) {
270 if (DEBUG) Log.v(TAG, "Connected to Google transport");
271 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
272 }
273
274 public void onServiceDisconnected(ComponentName name) {
275 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
276 mGoogleTransport = null;
277 }
278 };
279
Joe Onorato8ad02812009-05-13 01:41:44 -0400280 // ----- Run the actual backup process asynchronously -----
281
Christopher Tate181fafa2009-05-14 11:12:14 -0700282 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400283 public void handleMessage(Message msg) {
284
285 switch (msg.what) {
286 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700287 {
288 IBackupTransport transport = getTransport(mTransportId);
289 if (transport == null) {
290 Log.v(TAG, "Backup requested but no transport available");
291 break;
292 }
293
Joe Onorato8ad02812009-05-13 01:41:44 -0400294 // snapshot the pending-backup set and work on that
Christopher Tatecde87f42009-06-12 12:55:53 -0700295 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400296 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700297 if (mPendingBackups.size() == 0) {
298 Log.v(TAG, "Backup requested but nothing pending");
299 break;
300 }
301
Joe Onoratod2110db2009-05-19 13:41:21 -0700302 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700303 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700304 for (BackupRequest b: mPendingBackups.values()) {
305 mBackupQueue.add(b);
306 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700307 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400308 }
Christopher Tateace7f092009-06-15 18:07:25 -0700309
310 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700311 if (mJournalStream != null) {
312 try {
313 mJournalStream.close();
314 } catch (IOException e) {
315 // don't need to do anything
316 }
317 makeJournalLocked();
318 }
319
320 // At this point, we have started a new journal file, and the old
321 // file identity is being passed to the backup processing thread.
322 // When it completes successfully, that old journal file will be
323 // deleted. If we crash prior to that, the old journal is parsed
324 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400325 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700326
327 (new PerformBackupThread(transport, mBackupQueue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700328 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700329 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700330
331 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400332 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700333
334 case MSG_RUN_RESTORE:
335 {
336 int token = msg.arg1;
337 IBackupTransport transport = (IBackupTransport)msg.obj;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700338 (new PerformRestoreThread(transport, token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700339 break;
340 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400341 }
342 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400343 }
344
Christopher Tate181fafa2009-05-14 11:12:14 -0700345 // Add the backup agents in the given package to our set of known backup participants.
346 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700347 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700348 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700349 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700350 List<ApplicationInfo> targetApps = allAgentApps();
351 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700352 }
353
Christopher Tate181fafa2009-05-14 11:12:14 -0700354 private void addPackageParticipantsLockedInner(String packageName,
355 List<ApplicationInfo> targetApps) {
356 if (DEBUG) {
357 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
358 for (ApplicationInfo a : targetApps) {
359 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
360 }
361 }
362
363 for (ApplicationInfo app : targetApps) {
364 if (packageName == null || app.packageName.equals(packageName)) {
365 int uid = app.uid;
366 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700367 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700368 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700369 mBackupParticipants.put(uid, set);
370 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700371 set.add(app);
Christopher Tate6785dd82009-06-18 15:58:25 -0700372 backUpPackageManagerData();
Christopher Tate3799bc22009-05-06 16:13:56 -0700373 }
Christopher Tate487529a2009-04-29 14:03:25 -0700374 }
375 }
376
Christopher Tate6785dd82009-06-18 15:58:25 -0700377 // Remove the given package's entry from our known active set. If
378 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700379 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700380 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700381 List<ApplicationInfo> allApps = null;
382 if (packageName != null) {
383 allApps = new ArrayList<ApplicationInfo>();
384 try {
385 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
386 allApps.add(app);
387 } catch (Exception e) {
388 // just skip it
389 }
390 } else {
391 // all apps with agents
392 allApps = allAgentApps();
393 }
394 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700395 }
396
Joe Onorato8ad02812009-05-13 01:41:44 -0400397 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700398 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700399 if (DEBUG) {
400 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
401 + ") removing " + agents.size() + " entries");
402 for (ApplicationInfo a : agents) {
403 Log.v(TAG, " - " + a);
404 }
405 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700406 for (ApplicationInfo app : agents) {
407 if (packageName == null || app.packageName.equals(packageName)) {
408 int uid = app.uid;
409 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700410 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700411 // Find the existing entry with the same package name, and remove it.
412 // We can't just remove(app) because the instances are different.
413 for (ApplicationInfo entry: set) {
414 if (entry.packageName.equals(app.packageName)) {
415 set.remove(entry);
Christopher Tate6785dd82009-06-18 15:58:25 -0700416 backUpPackageManagerData();
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700417 break;
418 }
419 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700420 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700421 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700422 }
423 }
424 }
425 }
426
Christopher Tate181fafa2009-05-14 11:12:14 -0700427 // Returns the set of all applications that define an android:backupAgent attribute
428 private List<ApplicationInfo> allAgentApps() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700429 // !!! TODO: cache this and regenerate only when necessary
Christopher Tate181fafa2009-05-14 11:12:14 -0700430 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
431 int N = allApps.size();
432 if (N > 0) {
433 for (int a = N-1; a >= 0; a--) {
434 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700435 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
436 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700437 allApps.remove(a);
438 }
439 }
440 }
441 return allApps;
442 }
Christopher Tateaa088442009-06-16 18:25:46 -0700443
Christopher Tate3799bc22009-05-06 16:13:56 -0700444 // Reset the given package's known backup participants. Unlike add/remove, the update
445 // action cannot be passed a null package name.
446 void updatePackageParticipantsLocked(String packageName) {
447 if (packageName == null) {
448 Log.e(TAG, "updatePackageParticipants called with null package name");
449 return;
450 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700451 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700452
453 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700454 List<ApplicationInfo> allApps = allAgentApps();
455 removePackageParticipantsLockedInner(packageName, allApps);
456 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700457 }
458
Christopher Tate6785dd82009-06-18 15:58:25 -0700459 private void backUpPackageManagerData() {
460 // No need to schedule a backup just for the metadata; just piggyback on
461 // the next actual data backup.
462 synchronized(this) {
463 mDoPackageManager = true;
464 }
465 }
466
467 // The queue lock should be held when scheduling a backup pass
468 private void scheduleBackupPassLocked(long timeFromNowMillis) {
469 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
470 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
471 }
472
Dan Egnor87a02bc2009-06-17 02:30:10 -0700473 // Return the given transport
474 private IBackupTransport getTransport(int transportID) {
Christopher Tate8c850b72009-06-07 19:33:20 -0700475 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700476 case BackupManager.TRANSPORT_LOCAL:
Christopher Tate6785dd82009-06-18 15:58:25 -0700477 Log.v(TAG, "Supplying local transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700478 return mLocalTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700479
480 case BackupManager.TRANSPORT_GOOGLE:
Christopher Tate6785dd82009-06-18 15:58:25 -0700481 Log.v(TAG, "Supplying Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700482 return mGoogleTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700483
484 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700485 Log.e(TAG, "Asked for unknown transport " + transportID);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700486 return null;
Christopher Tate8c850b72009-06-07 19:33:20 -0700487 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700488 }
489
Christopher Tatedf01dea2009-06-09 20:45:02 -0700490 // fire off a backup agent, blocking until it attaches or times out
491 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
492 IBackupAgent agent = null;
493 synchronized(mAgentConnectLock) {
494 mConnecting = true;
495 mConnectedAgent = null;
496 try {
497 if (mActivityManager.bindBackupAgent(app, mode)) {
498 Log.d(TAG, "awaiting agent for " + app);
499
500 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700501 // only wait 10 seconds for the clear data to happen
502 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
503 while (mConnecting && mConnectedAgent == null
504 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700505 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700506 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700507 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700508 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700509 return null;
510 }
511 }
512
513 // if we timed out with no connect, abort and move on
514 if (mConnecting == true) {
515 Log.w(TAG, "Timeout waiting for agent " + app);
516 return null;
517 }
518 agent = mConnectedAgent;
519 }
520 } catch (RemoteException e) {
521 // can't happen
522 }
523 }
524 return agent;
525 }
526
Christopher Tatec7b31e32009-06-10 15:49:30 -0700527 // clear an application's data, blocking until the operation completes or times out
528 void clearApplicationDataSynchronous(String packageName) {
529 ClearDataObserver observer = new ClearDataObserver();
530
531 synchronized(mClearDataLock) {
532 mClearingData = true;
533 mPackageManager.clearApplicationUserData(packageName, observer);
534
535 // only wait 10 seconds for the clear data to happen
536 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
537 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
538 try {
539 mClearDataLock.wait(5000);
540 } catch (InterruptedException e) {
541 // won't happen, but still.
542 mClearingData = false;
543 }
544 }
545 }
546 }
547
548 class ClearDataObserver extends IPackageDataObserver.Stub {
549 public void onRemoveCompleted(String packageName, boolean succeeded)
550 throws android.os.RemoteException {
551 synchronized(mClearDataLock) {
552 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700553 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700554 }
555 }
556 }
557
Christopher Tate043dadc2009-06-02 16:11:00 -0700558 // ----- Back up a set of applications via a worker thread -----
559
560 class PerformBackupThread extends Thread {
561 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700562 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700563 ArrayList<BackupRequest> mQueue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700564 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700565
Christopher Tateaa088442009-06-16 18:25:46 -0700566 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700567 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700568 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700569 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700570 mJournal = journal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700571 }
572
573 @Override
574 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700575 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
576
Christopher Tatedf01dea2009-06-09 20:45:02 -0700577 // start up the transport
578 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700579 mTransport.startSession();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700580 } catch (Exception e) {
581 Log.e(TAG, "Error session transport");
582 e.printStackTrace();
583 return;
584 }
585
Christopher Tate6785dd82009-06-18 15:58:25 -0700586 // The transport is up and running. First, back up the package manager
587 // metadata if necessary
588 boolean doPackageManager;
589 synchronized (BackupManagerService.this) {
590 doPackageManager = mDoPackageManager;
591 mDoPackageManager = false;
592 }
593 if (doPackageManager) {
594 // The package manager doesn't have a proper <application> etc, but since
595 // it's running here in the system process we can just set up its agent
596 // directly and use a synthetic BackupRequest.
597 if (DEBUG) Log.i(TAG, "Running PM backup pass as well");
598
599 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
600 mPackageManager, allAgentApps());
601 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
602 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
603 processOneBackup(pmRequest,
604 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
605 mTransport);
606 }
607
608 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700609 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700610
611 // Finally, tear down the transport
612 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700613 mTransport.endSession();
Christopher Tate043dadc2009-06-02 16:11:00 -0700614 } catch (Exception e) {
615 Log.e(TAG, "Error ending transport");
616 e.printStackTrace();
617 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700618
619 if (!mJournal.delete()) {
620 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
621 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700622 }
623
624 private void doQueuedBackups(IBackupTransport transport) {
625 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700626 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700627
628 IBackupAgent agent = null;
629 int mode = (request.fullBackup)
630 ? IApplicationThread.BACKUP_MODE_FULL
631 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
632 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700633 agent = bindToAgentSynchronous(request.appInfo, mode);
634 if (agent != null) {
635 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700636 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700637
638 // unbind even on timeout, just in case
639 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700640 } catch (SecurityException ex) {
641 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700642 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700643 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700644 Log.v(TAG, "bind/backup threw");
645 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700646 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700647
Christopher Tate043dadc2009-06-02 16:11:00 -0700648 }
649 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700650
651 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
652 final String packageName = request.appInfo.packageName;
653 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
654
655 try {
656 // Look up the package info & signatures. This is first so that if it
657 // throws an exception, there's no file setup yet that would need to
658 // be unraveled.
659 PackageInfo packInfo = mPackageManager.getPackageInfo(packageName,
660 PackageManager.GET_SIGNATURES);
661
662 // !!! TODO: get the state file dir from the transport
663 File savedStateName = new File(mStateDir, packageName);
664 File backupDataName = new File(mDataDir, packageName + ".data");
665 File newStateName = new File(mStateDir, packageName + ".new");
666
667 // In a full backup, we pass a null ParcelFileDescriptor as
668 // the saved-state "file"
669 ParcelFileDescriptor savedState = (request.fullBackup) ? null
670 : ParcelFileDescriptor.open(savedStateName,
671 ParcelFileDescriptor.MODE_READ_ONLY |
672 ParcelFileDescriptor.MODE_CREATE);
673
674 backupDataName.delete();
675 ParcelFileDescriptor backupData =
676 ParcelFileDescriptor.open(backupDataName,
677 ParcelFileDescriptor.MODE_READ_WRITE |
678 ParcelFileDescriptor.MODE_CREATE);
679
680 newStateName.delete();
681 ParcelFileDescriptor newState =
682 ParcelFileDescriptor.open(newStateName,
683 ParcelFileDescriptor.MODE_READ_WRITE |
684 ParcelFileDescriptor.MODE_CREATE);
685
686 // Run the target's backup pass
687 boolean success = false;
688 try {
689 agent.doBackup(savedState, backupData, newState);
690 success = true;
691 } finally {
692 if (savedState != null) {
693 savedState.close();
694 }
695 backupData.close();
696 newState.close();
697 }
698
699 // Now propagate the newly-backed-up data to the transport
700 if (success) {
701 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
702 backupData =
703 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
704 int error = transport.performBackup(packInfo, backupData);
705
706 // !!! TODO: After successful transport, delete the now-stale data
707 // and juggle the files so that next time the new state is passed
708 //backupDataName.delete();
709 newStateName.renameTo(savedStateName);
710 }
711 } catch (NameNotFoundException e) {
712 Log.e(TAG, "Package not found on backup: " + packageName);
713 } catch (FileNotFoundException fnf) {
714 Log.w(TAG, "File not found on backup: ");
715 fnf.printStackTrace();
716 } catch (RemoteException e) {
717 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
718 e.printStackTrace();
719 } catch (Exception e) {
720 Log.w(TAG, "Final exception guard in backup: ");
721 e.printStackTrace();
722 }
723 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700724 }
725
Christopher Tatedf01dea2009-06-09 20:45:02 -0700726
727 // ----- Restore handling -----
728
729 // Is the given package restorable on this device? Returns the on-device app's
730 // ApplicationInfo struct if it is; null if not.
731 //
732 // !!! TODO: also consider signatures
Christopher Tatec7b31e32009-06-10 15:49:30 -0700733 PackageInfo isRestorable(PackageInfo packageInfo) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700734 if (packageInfo.packageName != null) {
735 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700736 PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
Christopher Tatedf01dea2009-06-09 20:45:02 -0700737 PackageManager.GET_SIGNATURES);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700738 if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700739 return app;
740 }
741 } catch (Exception e) {
742 // doesn't exist on this device, or other error -- just ignore it.
743 }
744 }
745 return null;
746 }
747
748 class PerformRestoreThread extends Thread {
749 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700750 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700751 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700752
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700753 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700754 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700755 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700756 }
757
758 @Override
759 public void run() {
760 /**
761 * Restore sequence:
762 *
763 * 1. start up the transport session
764 * 2. get the restore set description for our identity
765 * 3. for each app in the restore set:
766 * 3.a. if it's restorable on this device, add it to the restore queue
767 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700768 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700769 * 4.b. get the restore data for the app from the transport
770 * 4.c. launch the backup agent for the app
771 * 4.d. agent.doRestore() with the data from the server
772 * 4.e. unbind the agent [and kill the app?]
773 * 5. shut down the transport
774 */
775
776 int err = -1;
777 try {
778 err = mTransport.startSession();
779 } catch (Exception e) {
780 Log.e(TAG, "Error starting transport for restore");
781 e.printStackTrace();
782 }
783
784 if (err == 0) {
Christopher Tate6785dd82009-06-18 15:58:25 -0700785 // !!! TODO: do the package manager signatures restore first
786
Christopher Tatedf01dea2009-06-09 20:45:02 -0700787 // build the set of apps to restore
788 try {
789 RestoreSet[] images = mTransport.getAvailableRestoreSets();
790 if (images.length > 0) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700791 // !!! TODO: pick out the set for this token
Christopher Tatec7b31e32009-06-10 15:49:30 -0700792 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700793
794 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700795 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
796 HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700797 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700798 // get the real PackageManager idea of the package
799 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700800 if (app != null) {
801 appsToRestore.add(app);
802 }
803 }
804
805 // now run the restore queue
806 doQueuedRestores(appsToRestore);
807 }
808 } catch (RemoteException e) {
809 // can't happen; transports run locally
810 }
811
812 // done; shut down the transport
813 try {
814 mTransport.endSession();
815 } catch (Exception e) {
816 Log.e(TAG, "Error ending transport for restore");
817 e.printStackTrace();
818 }
819 }
820
821 // even if the initial session startup failed, report that we're done here
822 }
823
824 // restore each app in the queue
Christopher Tatec7b31e32009-06-10 15:49:30 -0700825 void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
826 for (PackageInfo app : appsToRestore) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700827 Log.d(TAG, "starting agent for restore of " + app);
828
Christopher Tatedf01dea2009-06-09 20:45:02 -0700829 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700830 // Remove the app's data first
831 clearApplicationDataSynchronous(app.packageName);
832
833 // Now perform the restore into the clean app
834 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
835 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700836 if (agent != null) {
837 processOneRestore(app, agent);
838 }
839
840 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700841 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700842 } catch (SecurityException ex) {
843 // Try for the next one.
844 Log.d(TAG, "error in bind", ex);
845 } catch (RemoteException e) {
846 // can't happen
847 }
848
849 }
850 }
851
Christopher Tatec7b31e32009-06-10 15:49:30 -0700852 // Do the guts of a restore of one application, derived from the 'mImage'
853 // restore set via the 'mTransport' transport.
854 void processOneRestore(PackageInfo app, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700855 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700856 final String packageName = app.packageName;
857
858 // !!! TODO: get the dirs from the transport
859 File backupDataName = new File(mDataDir, packageName + ".restore");
860 backupDataName.delete();
861 try {
862 ParcelFileDescriptor backupData =
863 ParcelFileDescriptor.open(backupDataName,
864 ParcelFileDescriptor.MODE_READ_WRITE |
865 ParcelFileDescriptor.MODE_CREATE);
866
867 // Run the transport's restore pass
868 // Run the target's backup pass
869 int err = -1;
870 try {
871 err = mTransport.getRestoreData(mImage.token, app, backupData);
872 } catch (RemoteException e) {
873 // can't happen
874 } finally {
875 backupData.close();
876 }
877
878 // Okay, we have the data. Now have the agent do the restore.
879 File newStateName = new File(mStateDir, packageName + ".new");
880 ParcelFileDescriptor newState =
881 ParcelFileDescriptor.open(newStateName,
882 ParcelFileDescriptor.MODE_READ_WRITE |
883 ParcelFileDescriptor.MODE_CREATE);
884
885 backupData = ParcelFileDescriptor.open(backupDataName,
886 ParcelFileDescriptor.MODE_READ_ONLY);
887
888 boolean success = false;
889 try {
890 agent.doRestore(backupData, newState);
891 success = true;
892 } catch (Exception e) {
893 Log.e(TAG, "Restore failed for " + packageName);
894 e.printStackTrace();
895 } finally {
896 newState.close();
897 backupData.close();
898 }
899
900 // if everything went okay, remember the recorded state now
901 if (success) {
902 File savedStateName = new File(mStateDir, packageName);
903 newStateName.renameTo(savedStateName);
904 }
905 } catch (FileNotFoundException fnfe) {
906 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
907 } catch (IOException ioe) {
908 Log.e(TAG, "Unable to process restore file: " + ioe);
909 } catch (Exception e) {
910 Log.e(TAG, "Final exception guard in restore:");
911 e.printStackTrace();
912 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700913 }
914 }
915
916
Christopher Tate487529a2009-04-29 14:03:25 -0700917 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700918
Christopher Tatea8bf8152009-04-30 11:36:21 -0700919 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700920 // Record that we need a backup pass for the caller. Since multiple callers
921 // may share a uid, we need to note all candidates within that uid and schedule
922 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700923
924 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700925
926 // If the caller does not hold the BACKUP permission, it can only request a
927 // backup of its own data.
928 HashSet<ApplicationInfo> targets;
929 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
930 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
931 targets = mBackupParticipants.get(Binder.getCallingUid());
932 } else {
933 // a caller with full permission can ask to back up any participating app
934 // !!! TODO: allow backup of ANY app?
935 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
936 targets = new HashSet<ApplicationInfo>();
937 int N = mBackupParticipants.size();
938 for (int i = 0; i < N; i++) {
939 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
940 if (s != null) {
941 targets.addAll(s);
942 }
943 }
944 }
Christopher Tate487529a2009-04-29 14:03:25 -0700945 if (targets != null) {
946 synchronized (mQueueLock) {
947 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -0700948 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -0700949 // validate the caller-supplied package name against the known set of
950 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -0700951 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -0400952 // Add the caller to the set of pending backups. If there is
953 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -0700954 BackupRequest req = new BackupRequest(app, false);
955 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -0700956
957 // Journal this request in case of crash
958 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700959 }
960 }
961
Christopher Tate181fafa2009-05-14 11:12:14 -0700962 if (DEBUG) {
963 int numKeys = mPendingBackups.size();
964 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
965 for (BackupRequest b : mPendingBackups.values()) {
966 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
967 }
968 }
Christopher Tate487529a2009-04-29 14:03:25 -0700969 // Schedule a backup pass in a few minutes. As backup-eligible data
970 // keeps changing, continue to defer the backup pass until things
971 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -0700972 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -0700973 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700974 } else {
975 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700976 }
977 }
Christopher Tate46758122009-05-06 11:22:00 -0700978
Christopher Tatecde87f42009-06-12 12:55:53 -0700979 private void writeToJournalLocked(String str) {
980 if (mJournalStream != null) {
981 try {
982 mJournalStream.writeUTF(str);
983 } catch (IOException e) {
984 Log.e(TAG, "Error writing to backup journal");
985 mJournalStream = null;
986 mJournal = null;
987 }
988 }
989 }
990
Christopher Tateace7f092009-06-15 18:07:25 -0700991 // Run a backup pass immediately for any applications that have declared
992 // that they have pending updates.
993 public void backupNow() throws RemoteException {
994 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -0700995
Christopher Tateace7f092009-06-15 18:07:25 -0700996 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -0700997 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -0700998 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -0700999 }
1000 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001001
Christopher Tateace7f092009-06-15 18:07:25 -07001002 // Report the currently active transport
1003 public int getCurrentTransport() {
1004 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1005 return mTransportId;
1006 }
1007
Christopher Tate043dadc2009-06-02 16:11:00 -07001008 // Select which transport to use for the next backup operation
1009 public int selectBackupTransport(int transportId) {
1010 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1011
Dan Egnor87a02bc2009-06-17 02:30:10 -07001012 int prevTransport = mTransportId;
1013 mTransportId = transportId;
Christopher Tate043dadc2009-06-02 16:11:00 -07001014 return prevTransport;
1015 }
1016
1017 // Callback: a requested backup agent has been instantiated. This should only
1018 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001019 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001020 synchronized(mAgentConnectLock) {
1021 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1022 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1023 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1024 mConnectedAgent = agent;
1025 mConnecting = false;
1026 } else {
1027 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1028 + " claiming agent connected");
1029 }
1030 mAgentConnectLock.notifyAll();
1031 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001032 }
1033
1034 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1035 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001036 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001037 public void agentDisconnected(String packageName) {
1038 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001039 synchronized(mAgentConnectLock) {
1040 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1041 mConnectedAgent = null;
1042 mConnecting = false;
1043 } else {
1044 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1045 + " claiming agent disconnected");
1046 }
1047 mAgentConnectLock.notifyAll();
1048 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001049 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001050
Christopher Tate8c850b72009-06-07 19:33:20 -07001051 // Hand off a restore session
1052 public IRestoreSession beginRestoreSession(int transportID) {
1053 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001054
1055 synchronized(this) {
1056 if (mActiveRestoreSession != null) {
1057 Log.d(TAG, "Restore session requested but one already active");
1058 return null;
1059 }
1060 mActiveRestoreSession = new RestoreSession(transportID);
1061 }
1062 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001063 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001064
Christopher Tate9b3905c2009-06-08 15:24:01 -07001065 // ----- Restore session -----
1066
1067 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001068 private static final String TAG = "RestoreSession";
1069
Christopher Tate9b3905c2009-06-08 15:24:01 -07001070 private IBackupTransport mRestoreTransport = null;
1071 RestoreSet[] mRestoreSets = null;
1072
1073 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001074 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001075 }
1076
1077 // --- Binder interface ---
1078 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001079 mContext.enforceCallingPermission("android.permission.BACKUP",
1080 "getAvailableRestoreSets");
1081
Christopher Tatef68eb502009-06-16 11:02:01 -07001082 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001083 synchronized(this) {
1084 if (mRestoreSets == null) {
1085 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1086 }
1087 return mRestoreSets;
1088 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001089 } catch (RuntimeException e) {
1090 Log.d(TAG, "getAvailableRestoreSets exception");
1091 e.printStackTrace();
1092 throw e;
1093 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001094 }
1095
1096 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001097 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1098
1099 if (mRestoreSets != null) {
1100 for (int i = 0; i < mRestoreSets.length; i++) {
1101 if (token == mRestoreSets[i].token) {
1102 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1103 mRestoreTransport);
1104 msg.arg1 = token;
1105 mBackupHandler.sendMessage(msg);
1106 return 0;
1107 }
1108 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001109 } else {
1110 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001111 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001112 return -1;
1113 }
1114
1115 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001116 mContext.enforceCallingPermission("android.permission.BACKUP",
1117 "endRestoreSession");
1118
Christopher Tate9b3905c2009-06-08 15:24:01 -07001119 mRestoreTransport.endSession();
1120 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001121 synchronized(BackupManagerService.this) {
1122 if (BackupManagerService.this.mActiveRestoreSession == this) {
1123 BackupManagerService.this.mActiveRestoreSession = null;
1124 } else {
1125 Log.e(TAG, "ending non-current restore session");
1126 }
1127 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001128 }
1129 }
1130
Christopher Tate043dadc2009-06-02 16:11:00 -07001131
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001132 @Override
1133 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1134 synchronized (mQueueLock) {
1135 int N = mBackupParticipants.size();
1136 pw.println("Participants:");
1137 for (int i=0; i<N; i++) {
1138 int uid = mBackupParticipants.keyAt(i);
1139 pw.print(" uid: ");
1140 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001141 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1142 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001143 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001144 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001145 }
1146 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001147 pw.println("Pending:");
1148 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
1149 while (br.hasNext()) {
1150 pw.print(" ");
1151 pw.println(br);
1152 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001153 }
1154 }
Christopher Tate487529a2009-04-29 14:03:25 -07001155}