blob: 6ee82606590806e437d95af802acc48e92a02130 [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 Tateabce4e82009-06-18 18:35:32 -070034import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070035import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070036import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070037import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070038import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070039import android.os.Handler;
40import android.os.IBinder;
41import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070042import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070043import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070044import android.os.RemoteException;
45import android.util.Log;
46import android.util.SparseArray;
47
48import android.backup.IBackupManager;
Christopher Tate8c850b72009-06-07 19:33:20 -070049import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070050import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070051import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070052
Christopher Tate9bbc21a2009-06-10 20:23:25 -070053import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070054import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070055
Christopher Tate6785dd82009-06-18 15:58:25 -070056import com.android.server.PackageManagerBackupAgent;
57
Christopher Tatecde87f42009-06-12 12:55:53 -070058import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070059import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070060import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070061import java.io.FileNotFoundException;
Christopher Tatec7b31e32009-06-10 15:49:30 -070062import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070063import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070064import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070065import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040066import java.util.ArrayList;
67import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070068import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070069import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070070import java.util.List;
71
72class BackupManagerService extends IBackupManager.Stub {
73 private static final String TAG = "BackupManagerService";
74 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070075
Christopher Tate6785dd82009-06-18 15:58:25 -070076 // Default time to wait after data changes before we back up the data
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070077 private static final long COLLECTION_INTERVAL = 1000;
78 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070079
80 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070081 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070082 private static final int MSG_RUN_RESTORE = 3;
Christopher Tatec7b31e32009-06-10 15:49:30 -070083
84 // Timeout interval for deciding that a bind or clear-data has taken too long
85 static final long TIMEOUT_INTERVAL = 10 * 1000;
86
Christopher Tate487529a2009-04-29 14:03:25 -070087 private Context mContext;
88 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070089 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070090 private final BackupHandler mBackupHandler = new BackupHandler();
91 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070092 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
93 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070094 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070095 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070096 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070097 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -070098
Christopher Tate181fafa2009-05-14 11:12:14 -070099 BackupRequest(ApplicationInfo app, boolean isFull) {
100 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700101 fullBackup = isFull;
102 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700103
104 public String toString() {
105 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
106 }
Christopher Tate46758122009-05-06 11:22:00 -0700107 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400108 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700109 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
110 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate6785dd82009-06-18 15:58:25 -0700111 // Do we need to back up the package manager metadata on the next pass?
112 private boolean mDoPackageManager;
113 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Joe Onorato8ad02812009-05-13 01:41:44 -0400114 // Backups that we have started. These are separate to prevent starvation
115 // if an app keeps re-enqueuing itself.
116 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -0700117 private final Object mQueueLock = new Object();
118
Christopher Tate043dadc2009-06-02 16:11:00 -0700119 // The thread performing the sequence of queued backups binds to each app's agent
120 // in succession. Bind notifications are asynchronously delivered through the
121 // Activity Manager; use this lock object to signal when a requested binding has
122 // completed.
123 private final Object mAgentConnectLock = new Object();
124 private IBackupAgent mConnectedAgent;
125 private volatile boolean mConnecting;
126
Christopher Tatec7b31e32009-06-10 15:49:30 -0700127 // A similar synchronicity mechanism around clearing apps' data for restore
128 private final Object mClearDataLock = new Object();
129 private volatile boolean mClearingData;
130
Christopher Tateaa088442009-06-16 18:25:46 -0700131 // Current active transport & restore session
Christopher Tate043dadc2009-06-02 16:11:00 -0700132 private int mTransportId;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700133 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700134 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700135
Christopher Tate22b87872009-05-04 16:41:53 -0700136 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700137 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700138 private File mJournalDir;
139 private File mJournal;
140 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700141
Christopher Tate487529a2009-04-29 14:03:25 -0700142 public BackupManagerService(Context context) {
143 mContext = context;
144 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700145 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700146
Christopher Tate22b87872009-05-04 16:41:53 -0700147 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700148 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700149 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700150 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700151
Christopher Tatecde87f42009-06-12 12:55:53 -0700152 // Set up the backup-request journaling
153 mJournalDir = new File(mStateDir, "pending");
154 mJournalDir.mkdirs();
155 makeJournalLocked(); // okay because no other threads are running yet
156
Christopher Tateabce4e82009-06-18 18:35:32 -0700157 // Build our mapping of uid to backup client services. This implicitly
158 // schedules a backup pass on the Package Manager metadata the first
159 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700160 synchronized (mBackupParticipants) {
161 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700162 }
163
Dan Egnor87a02bc2009-06-17 02:30:10 -0700164 // Set up our transport options and initialize the default transport
165 // TODO: Have transports register themselves somehow?
166 // TODO: Don't create transports that we don't need to?
167 mTransportId = BackupManager.TRANSPORT_GOOGLE;
168 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
169 mGoogleTransport = null;
170
171 // Attach to the Google backup transport.
172 Intent intent = new Intent().setComponent(new ComponentName(
173 "com.google.android.backup",
174 "com.google.android.backup.BackupTransportService"));
175 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700176
Christopher Tatecde87f42009-06-12 12:55:53 -0700177 // Now that we know about valid backup participants, parse any
178 // leftover journal files and schedule a new backup pass
179 parseLeftoverJournals();
180
Christopher Tate3799bc22009-05-06 16:13:56 -0700181 // Register for broadcasts about package install, etc., so we can
182 // update the provider list.
183 IntentFilter filter = new IntentFilter();
184 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
185 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
186 filter.addDataScheme("package");
187 mContext.registerReceiver(mBroadcastReceiver, filter);
188 }
189
Christopher Tatecde87f42009-06-12 12:55:53 -0700190 private void makeJournalLocked() {
191 try {
192 mJournal = File.createTempFile("journal", null, mJournalDir);
193 mJournalStream = new RandomAccessFile(mJournal, "rwd");
194 } catch (IOException e) {
195 Log.e(TAG, "Unable to write backup journals");
196 mJournal = null;
197 mJournalStream = null;
198 }
199 }
200
201 private void parseLeftoverJournals() {
202 if (mJournal != null) {
203 File[] allJournals = mJournalDir.listFiles();
204 for (File f : allJournals) {
205 if (f.compareTo(mJournal) != 0) {
206 // This isn't the current journal, so it must be a leftover. Read
207 // out the package names mentioned there and schedule them for
208 // backup.
209 try {
210 Log.i(TAG, "Found stale backup journal, scheduling:");
211 RandomAccessFile in = new RandomAccessFile(f, "r");
212 while (true) {
213 String packageName = in.readUTF();
214 Log.i(TAG, " + " + packageName);
215 dataChanged(packageName);
216 }
217 } catch (EOFException e) {
218 // no more data; we're done
219 } catch (Exception e) {
220 // can't read it or other error; just skip it
221 } finally {
222 // close/delete the file
223 f.delete();
224 }
225 }
226 }
227 }
228 }
229
Christopher Tate3799bc22009-05-06 16:13:56 -0700230 // ----- Track installation/removal of packages -----
231 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
232 public void onReceive(Context context, Intent intent) {
233 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
234
235 Uri uri = intent.getData();
236 if (uri == null) {
237 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700238 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700239 String pkgName = uri.getSchemeSpecificPart();
240 if (pkgName == null) {
241 return;
242 }
243
244 String action = intent.getAction();
245 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
246 synchronized (mBackupParticipants) {
247 Bundle extras = intent.getExtras();
248 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
249 // The package was just upgraded
250 updatePackageParticipantsLocked(pkgName);
251 } else {
252 // The package was just added
253 addPackageParticipantsLocked(pkgName);
254 }
255 }
256 }
257 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
258 Bundle extras = intent.getExtras();
259 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
260 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
261 } else {
262 synchronized (mBackupParticipants) {
263 removePackageParticipantsLocked(pkgName);
264 }
265 }
266 }
267 }
268 };
269
Dan Egnor87a02bc2009-06-17 02:30:10 -0700270 // ----- Track connection to GoogleBackupTransport service -----
271 ServiceConnection mGoogleConnection = new ServiceConnection() {
272 public void onServiceConnected(ComponentName name, IBinder service) {
273 if (DEBUG) Log.v(TAG, "Connected to Google transport");
274 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
275 }
276
277 public void onServiceDisconnected(ComponentName name) {
278 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
279 mGoogleTransport = null;
280 }
281 };
282
Joe Onorato8ad02812009-05-13 01:41:44 -0400283 // ----- Run the actual backup process asynchronously -----
284
Christopher Tate181fafa2009-05-14 11:12:14 -0700285 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400286 public void handleMessage(Message msg) {
287
288 switch (msg.what) {
289 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700290 {
291 IBackupTransport transport = getTransport(mTransportId);
292 if (transport == null) {
293 Log.v(TAG, "Backup requested but no transport available");
294 break;
295 }
296
Joe Onorato8ad02812009-05-13 01:41:44 -0400297 // snapshot the pending-backup set and work on that
Christopher Tatecde87f42009-06-12 12:55:53 -0700298 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400299 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700300 if (mPendingBackups.size() == 0) {
301 Log.v(TAG, "Backup requested but nothing pending");
302 break;
303 }
304
Joe Onoratod2110db2009-05-19 13:41:21 -0700305 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700306 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700307 for (BackupRequest b: mPendingBackups.values()) {
308 mBackupQueue.add(b);
309 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700310 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400311 }
Christopher Tateace7f092009-06-15 18:07:25 -0700312
313 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700314 if (mJournalStream != null) {
315 try {
316 mJournalStream.close();
317 } catch (IOException e) {
318 // don't need to do anything
319 }
320 makeJournalLocked();
321 }
322
323 // At this point, we have started a new journal file, and the old
324 // file identity is being passed to the backup processing thread.
325 // When it completes successfully, that old journal file will be
326 // deleted. If we crash prior to that, the old journal is parsed
327 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400328 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700329
330 (new PerformBackupThread(transport, mBackupQueue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700331 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700332 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700333
334 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400335 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700336
337 case MSG_RUN_RESTORE:
338 {
339 int token = msg.arg1;
340 IBackupTransport transport = (IBackupTransport)msg.obj;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700341 (new PerformRestoreThread(transport, token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700342 break;
343 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400344 }
345 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400346 }
347
Christopher Tate181fafa2009-05-14 11:12:14 -0700348 // Add the backup agents in the given package to our set of known backup participants.
349 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700350 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700351 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700352 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700353 List<ApplicationInfo> targetApps = allAgentApps();
354 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700355 }
356
Christopher Tate181fafa2009-05-14 11:12:14 -0700357 private void addPackageParticipantsLockedInner(String packageName,
358 List<ApplicationInfo> targetApps) {
359 if (DEBUG) {
360 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
361 for (ApplicationInfo a : targetApps) {
362 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
363 }
364 }
365
366 for (ApplicationInfo app : targetApps) {
367 if (packageName == null || app.packageName.equals(packageName)) {
368 int uid = app.uid;
369 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700370 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700371 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700372 mBackupParticipants.put(uid, set);
373 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700374 set.add(app);
Christopher Tate6785dd82009-06-18 15:58:25 -0700375 backUpPackageManagerData();
Christopher Tate3799bc22009-05-06 16:13:56 -0700376 }
Christopher Tate487529a2009-04-29 14:03:25 -0700377 }
378 }
379
Christopher Tate6785dd82009-06-18 15:58:25 -0700380 // Remove the given package's entry from our known active set. If
381 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700382 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700383 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700384 List<ApplicationInfo> allApps = null;
385 if (packageName != null) {
386 allApps = new ArrayList<ApplicationInfo>();
387 try {
388 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
389 allApps.add(app);
390 } catch (Exception e) {
391 // just skip it
392 }
393 } else {
394 // all apps with agents
395 allApps = allAgentApps();
396 }
397 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700398 }
399
Joe Onorato8ad02812009-05-13 01:41:44 -0400400 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700401 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700402 if (DEBUG) {
403 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
404 + ") removing " + agents.size() + " entries");
405 for (ApplicationInfo a : agents) {
406 Log.v(TAG, " - " + a);
407 }
408 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700409 for (ApplicationInfo app : agents) {
410 if (packageName == null || app.packageName.equals(packageName)) {
411 int uid = app.uid;
412 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700413 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700414 // Find the existing entry with the same package name, and remove it.
415 // We can't just remove(app) because the instances are different.
416 for (ApplicationInfo entry: set) {
417 if (entry.packageName.equals(app.packageName)) {
418 set.remove(entry);
Christopher Tate6785dd82009-06-18 15:58:25 -0700419 backUpPackageManagerData();
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700420 break;
421 }
422 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700423 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700424 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700425 }
426 }
427 }
428 }
429
Christopher Tate181fafa2009-05-14 11:12:14 -0700430 // Returns the set of all applications that define an android:backupAgent attribute
431 private List<ApplicationInfo> allAgentApps() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700432 // !!! TODO: cache this and regenerate only when necessary
Christopher Tate181fafa2009-05-14 11:12:14 -0700433 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
434 int N = allApps.size();
435 if (N > 0) {
436 for (int a = N-1; a >= 0; a--) {
437 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700438 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
439 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700440 allApps.remove(a);
441 }
442 }
443 }
444 return allApps;
445 }
Christopher Tateaa088442009-06-16 18:25:46 -0700446
Christopher Tate3799bc22009-05-06 16:13:56 -0700447 // Reset the given package's known backup participants. Unlike add/remove, the update
448 // action cannot be passed a null package name.
449 void updatePackageParticipantsLocked(String packageName) {
450 if (packageName == null) {
451 Log.e(TAG, "updatePackageParticipants called with null package name");
452 return;
453 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700454 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700455
456 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700457 List<ApplicationInfo> allApps = allAgentApps();
458 removePackageParticipantsLockedInner(packageName, allApps);
459 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700460 }
461
Christopher Tate6785dd82009-06-18 15:58:25 -0700462 private void backUpPackageManagerData() {
463 // No need to schedule a backup just for the metadata; just piggyback on
464 // the next actual data backup.
465 synchronized(this) {
466 mDoPackageManager = true;
467 }
468 }
469
470 // The queue lock should be held when scheduling a backup pass
471 private void scheduleBackupPassLocked(long timeFromNowMillis) {
472 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
473 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
474 }
475
Dan Egnor87a02bc2009-06-17 02:30:10 -0700476 // Return the given transport
477 private IBackupTransport getTransport(int transportID) {
Christopher Tate8c850b72009-06-07 19:33:20 -0700478 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700479 case BackupManager.TRANSPORT_LOCAL:
Christopher Tate6785dd82009-06-18 15:58:25 -0700480 Log.v(TAG, "Supplying local transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700481 return mLocalTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700482
483 case BackupManager.TRANSPORT_GOOGLE:
Christopher Tate6785dd82009-06-18 15:58:25 -0700484 Log.v(TAG, "Supplying Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700485 return mGoogleTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700486
487 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700488 Log.e(TAG, "Asked for unknown transport " + transportID);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700489 return null;
Christopher Tate8c850b72009-06-07 19:33:20 -0700490 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700491 }
492
Christopher Tatedf01dea2009-06-09 20:45:02 -0700493 // fire off a backup agent, blocking until it attaches or times out
494 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
495 IBackupAgent agent = null;
496 synchronized(mAgentConnectLock) {
497 mConnecting = true;
498 mConnectedAgent = null;
499 try {
500 if (mActivityManager.bindBackupAgent(app, mode)) {
501 Log.d(TAG, "awaiting agent for " + app);
502
503 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700504 // only wait 10 seconds for the clear data to happen
505 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
506 while (mConnecting && mConnectedAgent == null
507 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700508 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700509 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700510 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700511 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700512 return null;
513 }
514 }
515
516 // if we timed out with no connect, abort and move on
517 if (mConnecting == true) {
518 Log.w(TAG, "Timeout waiting for agent " + app);
519 return null;
520 }
521 agent = mConnectedAgent;
522 }
523 } catch (RemoteException e) {
524 // can't happen
525 }
526 }
527 return agent;
528 }
529
Christopher Tatec7b31e32009-06-10 15:49:30 -0700530 // clear an application's data, blocking until the operation completes or times out
531 void clearApplicationDataSynchronous(String packageName) {
532 ClearDataObserver observer = new ClearDataObserver();
533
534 synchronized(mClearDataLock) {
535 mClearingData = true;
536 mPackageManager.clearApplicationUserData(packageName, observer);
537
538 // only wait 10 seconds for the clear data to happen
539 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
540 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
541 try {
542 mClearDataLock.wait(5000);
543 } catch (InterruptedException e) {
544 // won't happen, but still.
545 mClearingData = false;
546 }
547 }
548 }
549 }
550
551 class ClearDataObserver extends IPackageDataObserver.Stub {
552 public void onRemoveCompleted(String packageName, boolean succeeded)
553 throws android.os.RemoteException {
554 synchronized(mClearDataLock) {
555 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700556 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700557 }
558 }
559 }
560
Christopher Tate043dadc2009-06-02 16:11:00 -0700561 // ----- Back up a set of applications via a worker thread -----
562
563 class PerformBackupThread extends Thread {
564 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700565 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700566 ArrayList<BackupRequest> mQueue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700567 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700568
Christopher Tateaa088442009-06-16 18:25:46 -0700569 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700570 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700571 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700572 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700573 mJournal = journal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700574 }
575
576 @Override
577 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700578 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
579
Christopher Tatedf01dea2009-06-09 20:45:02 -0700580 // start up the transport
581 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700582 mTransport.startSession();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700583 } catch (Exception e) {
584 Log.e(TAG, "Error session transport");
585 e.printStackTrace();
586 return;
587 }
588
Christopher Tate6785dd82009-06-18 15:58:25 -0700589 // The transport is up and running. First, back up the package manager
590 // metadata if necessary
591 boolean doPackageManager;
592 synchronized (BackupManagerService.this) {
593 doPackageManager = mDoPackageManager;
594 mDoPackageManager = false;
595 }
596 if (doPackageManager) {
597 // The package manager doesn't have a proper <application> etc, but since
598 // it's running here in the system process we can just set up its agent
599 // directly and use a synthetic BackupRequest.
600 if (DEBUG) Log.i(TAG, "Running PM backup pass as well");
601
602 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
603 mPackageManager, allAgentApps());
604 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
605 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
606 processOneBackup(pmRequest,
607 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
608 mTransport);
609 }
610
611 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700612 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700613
614 // Finally, tear down the transport
615 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700616 mTransport.endSession();
Christopher Tate043dadc2009-06-02 16:11:00 -0700617 } catch (Exception e) {
618 Log.e(TAG, "Error ending transport");
619 e.printStackTrace();
620 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700621
622 if (!mJournal.delete()) {
623 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
624 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700625 }
626
627 private void doQueuedBackups(IBackupTransport transport) {
628 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700629 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700630
631 IBackupAgent agent = null;
632 int mode = (request.fullBackup)
633 ? IApplicationThread.BACKUP_MODE_FULL
634 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
635 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700636 agent = bindToAgentSynchronous(request.appInfo, mode);
637 if (agent != null) {
638 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700639 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700640
641 // unbind even on timeout, just in case
642 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700643 } catch (SecurityException ex) {
644 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700645 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700646 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700647 Log.v(TAG, "bind/backup threw");
648 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700649 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700650
Christopher Tate043dadc2009-06-02 16:11:00 -0700651 }
652 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700653
654 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
655 final String packageName = request.appInfo.packageName;
656 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
657
658 try {
659 // Look up the package info & signatures. This is first so that if it
660 // throws an exception, there's no file setup yet that would need to
661 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700662 PackageInfo packInfo;
663 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
664 // The metadata 'package' is synthetic
665 packInfo = new PackageInfo();
666 packInfo.packageName = packageName;
667 } else {
668 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700669 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700670 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700671
672 // !!! TODO: get the state file dir from the transport
673 File savedStateName = new File(mStateDir, packageName);
674 File backupDataName = new File(mDataDir, packageName + ".data");
675 File newStateName = new File(mStateDir, packageName + ".new");
676
677 // In a full backup, we pass a null ParcelFileDescriptor as
678 // the saved-state "file"
679 ParcelFileDescriptor savedState = (request.fullBackup) ? null
680 : ParcelFileDescriptor.open(savedStateName,
681 ParcelFileDescriptor.MODE_READ_ONLY |
682 ParcelFileDescriptor.MODE_CREATE);
683
684 backupDataName.delete();
685 ParcelFileDescriptor backupData =
686 ParcelFileDescriptor.open(backupDataName,
687 ParcelFileDescriptor.MODE_READ_WRITE |
688 ParcelFileDescriptor.MODE_CREATE);
689
690 newStateName.delete();
691 ParcelFileDescriptor newState =
692 ParcelFileDescriptor.open(newStateName,
693 ParcelFileDescriptor.MODE_READ_WRITE |
694 ParcelFileDescriptor.MODE_CREATE);
695
696 // Run the target's backup pass
697 boolean success = false;
698 try {
699 agent.doBackup(savedState, backupData, newState);
700 success = true;
701 } finally {
702 if (savedState != null) {
703 savedState.close();
704 }
705 backupData.close();
706 newState.close();
707 }
708
709 // Now propagate the newly-backed-up data to the transport
710 if (success) {
711 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
712 backupData =
713 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
714 int error = transport.performBackup(packInfo, backupData);
715
716 // !!! TODO: After successful transport, delete the now-stale data
717 // and juggle the files so that next time the new state is passed
718 //backupDataName.delete();
719 newStateName.renameTo(savedStateName);
720 }
721 } catch (NameNotFoundException e) {
722 Log.e(TAG, "Package not found on backup: " + packageName);
723 } catch (FileNotFoundException fnf) {
724 Log.w(TAG, "File not found on backup: ");
725 fnf.printStackTrace();
726 } catch (RemoteException e) {
727 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
728 e.printStackTrace();
729 } catch (Exception e) {
730 Log.w(TAG, "Final exception guard in backup: ");
731 e.printStackTrace();
732 }
733 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700734 }
735
Christopher Tatedf01dea2009-06-09 20:45:02 -0700736
737 // ----- Restore handling -----
738
739 // Is the given package restorable on this device? Returns the on-device app's
740 // ApplicationInfo struct if it is; null if not.
741 //
742 // !!! TODO: also consider signatures
Christopher Tatec7b31e32009-06-10 15:49:30 -0700743 PackageInfo isRestorable(PackageInfo packageInfo) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700744 if (packageInfo.packageName != null) {
745 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700746 PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
Christopher Tatedf01dea2009-06-09 20:45:02 -0700747 PackageManager.GET_SIGNATURES);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700748 if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700749 return app;
750 }
751 } catch (Exception e) {
752 // doesn't exist on this device, or other error -- just ignore it.
753 }
754 }
755 return null;
756 }
757
Christopher Tateabce4e82009-06-18 18:35:32 -0700758 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
759 // !!! TODO: this demands that every stored signature match one
760 // that is present on device, and does not demand the converse.
761 // Is this this right policy?
762 int nStored = storedSigs.length;
763 int nDevice = deviceSigs.length;
764
765 for (int i=0; i < nStored; i++) {
766 boolean match = false;
767 for (int j=0; j < nDevice; j++) {
768 if (storedSigs[i].equals(deviceSigs[j])) {
769 match = true;
770 break;
771 }
772 }
773 if (!match) {
774 return false;
775 }
776 }
777 return true;
778 }
779
Christopher Tatedf01dea2009-06-09 20:45:02 -0700780 class PerformRestoreThread extends Thread {
781 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700782 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700783 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700784
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700785 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700786 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700787 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700788 }
789
790 @Override
791 public void run() {
792 /**
793 * Restore sequence:
794 *
795 * 1. start up the transport session
796 * 2. get the restore set description for our identity
797 * 3. for each app in the restore set:
798 * 3.a. if it's restorable on this device, add it to the restore queue
799 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700800 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700801 * 4.b. get the restore data for the app from the transport
802 * 4.c. launch the backup agent for the app
803 * 4.d. agent.doRestore() with the data from the server
804 * 4.e. unbind the agent [and kill the app?]
805 * 5. shut down the transport
806 */
807
808 int err = -1;
809 try {
810 err = mTransport.startSession();
811 } catch (Exception e) {
812 Log.e(TAG, "Error starting transport for restore");
813 e.printStackTrace();
814 }
815
816 if (err == 0) {
Christopher Tate6785dd82009-06-18 15:58:25 -0700817 // !!! TODO: do the package manager signatures restore first
818
Christopher Tatedf01dea2009-06-09 20:45:02 -0700819 // build the set of apps to restore
820 try {
821 RestoreSet[] images = mTransport.getAvailableRestoreSets();
822 if (images.length > 0) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700823 // !!! TODO: pick out the set for this token
Christopher Tatec7b31e32009-06-10 15:49:30 -0700824 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700825
Christopher Tateabce4e82009-06-18 18:35:32 -0700826 // Pull the Package Manager metadata from the restore set first
827 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
828 mPackageManager, allAgentApps());
829 PackageInfo pmApp = new PackageInfo();
830 pmApp.packageName = PACKAGE_MANAGER_SENTINEL;
831 processOneRestore(pmApp, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
832
Christopher Tatedf01dea2009-06-09 20:45:02 -0700833 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700834 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
835 HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700836 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700837 // get the real PackageManager idea of the package
838 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700839 if (app != null) {
Christopher Tateabce4e82009-06-18 18:35:32 -0700840 // Validate against the backed-up signature block, too
841 Signature[] storedSigs
842 = pmAgent.getRestoredSignatures(app.packageName);
843 if (storedSigs != null) {
844 // !!! TODO: check app version here as well
845 if (signaturesMatch(storedSigs, app.signatures)) {
846 appsToRestore.add(app);
847 } else {
848 Log.w(TAG, "Sig mismatch on restore of " + app.packageName);
849 }
850 } else {
851 Log.i(TAG, "No stored sigs for " + app.packageName
852 + " so not restoring");
853 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700854 }
855 }
856
857 // now run the restore queue
858 doQueuedRestores(appsToRestore);
859 }
860 } catch (RemoteException e) {
861 // can't happen; transports run locally
862 }
863
864 // done; shut down the transport
865 try {
866 mTransport.endSession();
867 } catch (Exception e) {
868 Log.e(TAG, "Error ending transport for restore");
869 e.printStackTrace();
870 }
871 }
872
873 // even if the initial session startup failed, report that we're done here
874 }
875
876 // restore each app in the queue
Christopher Tatec7b31e32009-06-10 15:49:30 -0700877 void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
878 for (PackageInfo app : appsToRestore) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700879 Log.d(TAG, "starting agent for restore of " + app);
880
Christopher Tatedf01dea2009-06-09 20:45:02 -0700881 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700882 // Remove the app's data first
883 clearApplicationDataSynchronous(app.packageName);
884
885 // Now perform the restore into the clean app
886 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
887 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700888 if (agent != null) {
889 processOneRestore(app, agent);
890 }
891
892 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700893 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700894 } catch (SecurityException ex) {
895 // Try for the next one.
896 Log.d(TAG, "error in bind", ex);
897 } catch (RemoteException e) {
898 // can't happen
899 }
900
901 }
902 }
903
Christopher Tatec7b31e32009-06-10 15:49:30 -0700904 // Do the guts of a restore of one application, derived from the 'mImage'
905 // restore set via the 'mTransport' transport.
906 void processOneRestore(PackageInfo app, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700907 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700908 final String packageName = app.packageName;
909
910 // !!! TODO: get the dirs from the transport
911 File backupDataName = new File(mDataDir, packageName + ".restore");
912 backupDataName.delete();
913 try {
914 ParcelFileDescriptor backupData =
915 ParcelFileDescriptor.open(backupDataName,
916 ParcelFileDescriptor.MODE_READ_WRITE |
917 ParcelFileDescriptor.MODE_CREATE);
918
919 // Run the transport's restore pass
920 // Run the target's backup pass
921 int err = -1;
922 try {
923 err = mTransport.getRestoreData(mImage.token, app, backupData);
924 } catch (RemoteException e) {
925 // can't happen
926 } finally {
927 backupData.close();
928 }
929
930 // Okay, we have the data. Now have the agent do the restore.
931 File newStateName = new File(mStateDir, packageName + ".new");
932 ParcelFileDescriptor newState =
933 ParcelFileDescriptor.open(newStateName,
934 ParcelFileDescriptor.MODE_READ_WRITE |
935 ParcelFileDescriptor.MODE_CREATE);
936
937 backupData = ParcelFileDescriptor.open(backupDataName,
938 ParcelFileDescriptor.MODE_READ_ONLY);
939
940 boolean success = false;
941 try {
942 agent.doRestore(backupData, newState);
943 success = true;
944 } catch (Exception e) {
945 Log.e(TAG, "Restore failed for " + packageName);
946 e.printStackTrace();
947 } finally {
948 newState.close();
949 backupData.close();
950 }
951
952 // if everything went okay, remember the recorded state now
953 if (success) {
954 File savedStateName = new File(mStateDir, packageName);
955 newStateName.renameTo(savedStateName);
956 }
957 } catch (FileNotFoundException fnfe) {
958 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
959 } catch (IOException ioe) {
960 Log.e(TAG, "Unable to process restore file: " + ioe);
961 } catch (Exception e) {
962 Log.e(TAG, "Final exception guard in restore:");
963 e.printStackTrace();
964 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700965 }
966 }
967
968
Christopher Tate487529a2009-04-29 14:03:25 -0700969 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700970
Christopher Tatea8bf8152009-04-30 11:36:21 -0700971 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700972 // Record that we need a backup pass for the caller. Since multiple callers
973 // may share a uid, we need to note all candidates within that uid and schedule
974 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700975
976 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700977
978 // If the caller does not hold the BACKUP permission, it can only request a
979 // backup of its own data.
980 HashSet<ApplicationInfo> targets;
981 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
982 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
983 targets = mBackupParticipants.get(Binder.getCallingUid());
984 } else {
985 // a caller with full permission can ask to back up any participating app
986 // !!! TODO: allow backup of ANY app?
987 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
988 targets = new HashSet<ApplicationInfo>();
989 int N = mBackupParticipants.size();
990 for (int i = 0; i < N; i++) {
991 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
992 if (s != null) {
993 targets.addAll(s);
994 }
995 }
996 }
Christopher Tate487529a2009-04-29 14:03:25 -0700997 if (targets != null) {
998 synchronized (mQueueLock) {
999 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001000 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001001 // validate the caller-supplied package name against the known set of
1002 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001003 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001004 // Add the caller to the set of pending backups. If there is
1005 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001006 BackupRequest req = new BackupRequest(app, false);
1007 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001008
1009 // Journal this request in case of crash
1010 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001011 }
1012 }
1013
Christopher Tate181fafa2009-05-14 11:12:14 -07001014 if (DEBUG) {
1015 int numKeys = mPendingBackups.size();
1016 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1017 for (BackupRequest b : mPendingBackups.values()) {
1018 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1019 }
1020 }
Christopher Tate487529a2009-04-29 14:03:25 -07001021 // Schedule a backup pass in a few minutes. As backup-eligible data
1022 // keeps changing, continue to defer the backup pass until things
1023 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001024 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001025 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001026 } else {
1027 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001028 }
1029 }
Christopher Tate46758122009-05-06 11:22:00 -07001030
Christopher Tatecde87f42009-06-12 12:55:53 -07001031 private void writeToJournalLocked(String str) {
1032 if (mJournalStream != null) {
1033 try {
1034 mJournalStream.writeUTF(str);
1035 } catch (IOException e) {
1036 Log.e(TAG, "Error writing to backup journal");
1037 mJournalStream = null;
1038 mJournal = null;
1039 }
1040 }
1041 }
1042
Christopher Tateace7f092009-06-15 18:07:25 -07001043 // Run a backup pass immediately for any applications that have declared
1044 // that they have pending updates.
1045 public void backupNow() throws RemoteException {
1046 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001047
Christopher Tateace7f092009-06-15 18:07:25 -07001048 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001049 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001050 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001051 }
1052 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001053
Christopher Tateace7f092009-06-15 18:07:25 -07001054 // Report the currently active transport
1055 public int getCurrentTransport() {
1056 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001057 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001058 return mTransportId;
1059 }
1060
Christopher Tate043dadc2009-06-02 16:11:00 -07001061 // Select which transport to use for the next backup operation
1062 public int selectBackupTransport(int transportId) {
1063 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1064
Dan Egnor87a02bc2009-06-17 02:30:10 -07001065 int prevTransport = mTransportId;
1066 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001067 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001068 return prevTransport;
1069 }
1070
1071 // Callback: a requested backup agent has been instantiated. This should only
1072 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001073 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001074 synchronized(mAgentConnectLock) {
1075 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1076 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1077 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1078 mConnectedAgent = agent;
1079 mConnecting = false;
1080 } else {
1081 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1082 + " claiming agent connected");
1083 }
1084 mAgentConnectLock.notifyAll();
1085 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001086 }
1087
1088 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1089 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001090 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001091 public void agentDisconnected(String packageName) {
1092 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001093 synchronized(mAgentConnectLock) {
1094 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1095 mConnectedAgent = null;
1096 mConnecting = false;
1097 } else {
1098 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1099 + " claiming agent disconnected");
1100 }
1101 mAgentConnectLock.notifyAll();
1102 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001103 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001104
Christopher Tate8c850b72009-06-07 19:33:20 -07001105 // Hand off a restore session
1106 public IRestoreSession beginRestoreSession(int transportID) {
1107 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001108
1109 synchronized(this) {
1110 if (mActiveRestoreSession != null) {
1111 Log.d(TAG, "Restore session requested but one already active");
1112 return null;
1113 }
1114 mActiveRestoreSession = new RestoreSession(transportID);
1115 }
1116 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001117 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001118
Christopher Tate9b3905c2009-06-08 15:24:01 -07001119 // ----- Restore session -----
1120
1121 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001122 private static final String TAG = "RestoreSession";
1123
Christopher Tate9b3905c2009-06-08 15:24:01 -07001124 private IBackupTransport mRestoreTransport = null;
1125 RestoreSet[] mRestoreSets = null;
1126
1127 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001128 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001129 }
1130
1131 // --- Binder interface ---
1132 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001133 mContext.enforceCallingPermission("android.permission.BACKUP",
1134 "getAvailableRestoreSets");
1135
Christopher Tatef68eb502009-06-16 11:02:01 -07001136 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001137 synchronized(this) {
1138 if (mRestoreSets == null) {
1139 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1140 }
1141 return mRestoreSets;
1142 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001143 } catch (RuntimeException e) {
1144 Log.d(TAG, "getAvailableRestoreSets exception");
1145 e.printStackTrace();
1146 throw e;
1147 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001148 }
1149
1150 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001151 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1152
1153 if (mRestoreSets != null) {
1154 for (int i = 0; i < mRestoreSets.length; i++) {
1155 if (token == mRestoreSets[i].token) {
1156 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1157 mRestoreTransport);
1158 msg.arg1 = token;
1159 mBackupHandler.sendMessage(msg);
1160 return 0;
1161 }
1162 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001163 } else {
1164 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001165 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001166 return -1;
1167 }
1168
1169 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001170 mContext.enforceCallingPermission("android.permission.BACKUP",
1171 "endRestoreSession");
1172
Christopher Tate9b3905c2009-06-08 15:24:01 -07001173 mRestoreTransport.endSession();
1174 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001175 synchronized(BackupManagerService.this) {
1176 if (BackupManagerService.this.mActiveRestoreSession == this) {
1177 BackupManagerService.this.mActiveRestoreSession = null;
1178 } else {
1179 Log.e(TAG, "ending non-current restore session");
1180 }
1181 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001182 }
1183 }
1184
Christopher Tate043dadc2009-06-02 16:11:00 -07001185
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001186 @Override
1187 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1188 synchronized (mQueueLock) {
1189 int N = mBackupParticipants.size();
1190 pw.println("Participants:");
1191 for (int i=0; i<N; i++) {
1192 int uid = mBackupParticipants.keyAt(i);
1193 pw.print(" uid: ");
1194 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001195 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1196 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001197 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001198 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001199 }
1200 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001201 pw.println("Pending:");
1202 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
1203 while (br.hasNext()) {
1204 pw.print(" ");
1205 pw.println(br);
1206 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001207 }
1208 }
Christopher Tate487529a2009-04-29 14:03:25 -07001209}