blob: fa88111a2707f9178b189ef9aa069a2edabfd624 [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?
Joe Onorato5d605dc2009-06-18 18:23:43 -0700167 //mTransportId = BackupManager.TRANSPORT_LOCAL;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700168 mTransportId = BackupManager.TRANSPORT_GOOGLE;
169 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
170 mGoogleTransport = null;
171
172 // Attach to the Google backup transport.
173 Intent intent = new Intent().setComponent(new ComponentName(
174 "com.google.android.backup",
175 "com.google.android.backup.BackupTransportService"));
176 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700177
Christopher Tatecde87f42009-06-12 12:55:53 -0700178 // Now that we know about valid backup participants, parse any
179 // leftover journal files and schedule a new backup pass
180 parseLeftoverJournals();
181
Christopher Tate3799bc22009-05-06 16:13:56 -0700182 // Register for broadcasts about package install, etc., so we can
183 // update the provider list.
184 IntentFilter filter = new IntentFilter();
185 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
186 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
187 filter.addDataScheme("package");
188 mContext.registerReceiver(mBroadcastReceiver, filter);
189 }
190
Christopher Tatecde87f42009-06-12 12:55:53 -0700191 private void makeJournalLocked() {
192 try {
193 mJournal = File.createTempFile("journal", null, mJournalDir);
194 mJournalStream = new RandomAccessFile(mJournal, "rwd");
195 } catch (IOException e) {
196 Log.e(TAG, "Unable to write backup journals");
197 mJournal = null;
198 mJournalStream = null;
199 }
200 }
201
202 private void parseLeftoverJournals() {
203 if (mJournal != null) {
204 File[] allJournals = mJournalDir.listFiles();
205 for (File f : allJournals) {
206 if (f.compareTo(mJournal) != 0) {
207 // This isn't the current journal, so it must be a leftover. Read
208 // out the package names mentioned there and schedule them for
209 // backup.
210 try {
211 Log.i(TAG, "Found stale backup journal, scheduling:");
212 RandomAccessFile in = new RandomAccessFile(f, "r");
213 while (true) {
214 String packageName = in.readUTF();
215 Log.i(TAG, " + " + packageName);
216 dataChanged(packageName);
217 }
218 } catch (EOFException e) {
219 // no more data; we're done
220 } catch (Exception e) {
221 // can't read it or other error; just skip it
222 } finally {
223 // close/delete the file
224 f.delete();
225 }
226 }
227 }
228 }
229 }
230
Christopher Tate3799bc22009-05-06 16:13:56 -0700231 // ----- Track installation/removal of packages -----
232 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
233 public void onReceive(Context context, Intent intent) {
234 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
235
236 Uri uri = intent.getData();
237 if (uri == null) {
238 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700239 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700240 String pkgName = uri.getSchemeSpecificPart();
241 if (pkgName == null) {
242 return;
243 }
244
245 String action = intent.getAction();
246 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
247 synchronized (mBackupParticipants) {
248 Bundle extras = intent.getExtras();
249 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
250 // The package was just upgraded
251 updatePackageParticipantsLocked(pkgName);
252 } else {
253 // The package was just added
254 addPackageParticipantsLocked(pkgName);
255 }
256 }
257 }
258 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
259 Bundle extras = intent.getExtras();
260 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
261 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
262 } else {
263 synchronized (mBackupParticipants) {
264 removePackageParticipantsLocked(pkgName);
265 }
266 }
267 }
268 }
269 };
270
Dan Egnor87a02bc2009-06-17 02:30:10 -0700271 // ----- Track connection to GoogleBackupTransport service -----
272 ServiceConnection mGoogleConnection = new ServiceConnection() {
273 public void onServiceConnected(ComponentName name, IBinder service) {
274 if (DEBUG) Log.v(TAG, "Connected to Google transport");
275 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
276 }
277
278 public void onServiceDisconnected(ComponentName name) {
279 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
280 mGoogleTransport = null;
281 }
282 };
283
Joe Onorato8ad02812009-05-13 01:41:44 -0400284 // ----- Run the actual backup process asynchronously -----
285
Christopher Tate181fafa2009-05-14 11:12:14 -0700286 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400287 public void handleMessage(Message msg) {
288
289 switch (msg.what) {
290 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700291 {
292 IBackupTransport transport = getTransport(mTransportId);
293 if (transport == null) {
294 Log.v(TAG, "Backup requested but no transport available");
295 break;
296 }
297
Joe Onorato8ad02812009-05-13 01:41:44 -0400298 // snapshot the pending-backup set and work on that
Christopher Tatecde87f42009-06-12 12:55:53 -0700299 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400300 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700301 if (mPendingBackups.size() == 0) {
302 Log.v(TAG, "Backup requested but nothing pending");
303 break;
304 }
305
Joe Onoratod2110db2009-05-19 13:41:21 -0700306 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700307 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700308 for (BackupRequest b: mPendingBackups.values()) {
309 mBackupQueue.add(b);
310 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700311 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400312 }
Christopher Tateace7f092009-06-15 18:07:25 -0700313
314 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700315 if (mJournalStream != null) {
316 try {
317 mJournalStream.close();
318 } catch (IOException e) {
319 // don't need to do anything
320 }
321 makeJournalLocked();
322 }
323
324 // At this point, we have started a new journal file, and the old
325 // file identity is being passed to the backup processing thread.
326 // When it completes successfully, that old journal file will be
327 // deleted. If we crash prior to that, the old journal is parsed
328 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400329 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700330
331 (new PerformBackupThread(transport, mBackupQueue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700332 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700333 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700334
335 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400336 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700337
338 case MSG_RUN_RESTORE:
339 {
340 int token = msg.arg1;
341 IBackupTransport transport = (IBackupTransport)msg.obj;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700342 (new PerformRestoreThread(transport, token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700343 break;
344 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400345 }
346 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400347 }
348
Christopher Tate181fafa2009-05-14 11:12:14 -0700349 // Add the backup agents in the given package to our set of known backup participants.
350 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700351 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700352 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700353 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700354 List<ApplicationInfo> targetApps = allAgentApps();
355 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700356 }
357
Christopher Tate181fafa2009-05-14 11:12:14 -0700358 private void addPackageParticipantsLockedInner(String packageName,
359 List<ApplicationInfo> targetApps) {
360 if (DEBUG) {
361 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
362 for (ApplicationInfo a : targetApps) {
363 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
364 }
365 }
366
367 for (ApplicationInfo app : targetApps) {
368 if (packageName == null || app.packageName.equals(packageName)) {
369 int uid = app.uid;
370 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700371 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700372 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700373 mBackupParticipants.put(uid, set);
374 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700375 set.add(app);
Christopher Tate6785dd82009-06-18 15:58:25 -0700376 backUpPackageManagerData();
Christopher Tate3799bc22009-05-06 16:13:56 -0700377 }
Christopher Tate487529a2009-04-29 14:03:25 -0700378 }
379 }
380
Christopher Tate6785dd82009-06-18 15:58:25 -0700381 // Remove the given package's entry from our known active set. If
382 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700383 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700384 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700385 List<ApplicationInfo> allApps = null;
386 if (packageName != null) {
387 allApps = new ArrayList<ApplicationInfo>();
388 try {
389 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
390 allApps.add(app);
391 } catch (Exception e) {
392 // just skip it
393 }
394 } else {
395 // all apps with agents
396 allApps = allAgentApps();
397 }
398 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700399 }
400
Joe Onorato8ad02812009-05-13 01:41:44 -0400401 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700402 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700403 if (DEBUG) {
404 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
405 + ") removing " + agents.size() + " entries");
406 for (ApplicationInfo a : agents) {
407 Log.v(TAG, " - " + a);
408 }
409 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700410 for (ApplicationInfo app : agents) {
411 if (packageName == null || app.packageName.equals(packageName)) {
412 int uid = app.uid;
413 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700414 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700415 // Find the existing entry with the same package name, and remove it.
416 // We can't just remove(app) because the instances are different.
417 for (ApplicationInfo entry: set) {
418 if (entry.packageName.equals(app.packageName)) {
419 set.remove(entry);
Christopher Tate6785dd82009-06-18 15:58:25 -0700420 backUpPackageManagerData();
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700421 break;
422 }
423 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700424 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700425 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700426 }
427 }
428 }
429 }
430
Christopher Tate181fafa2009-05-14 11:12:14 -0700431 // Returns the set of all applications that define an android:backupAgent attribute
432 private List<ApplicationInfo> allAgentApps() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700433 // !!! TODO: cache this and regenerate only when necessary
Christopher Tate181fafa2009-05-14 11:12:14 -0700434 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
435 int N = allApps.size();
436 if (N > 0) {
437 for (int a = N-1; a >= 0; a--) {
438 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700439 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
440 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700441 allApps.remove(a);
442 }
443 }
444 }
445 return allApps;
446 }
Christopher Tateaa088442009-06-16 18:25:46 -0700447
Christopher Tate3799bc22009-05-06 16:13:56 -0700448 // Reset the given package's known backup participants. Unlike add/remove, the update
449 // action cannot be passed a null package name.
450 void updatePackageParticipantsLocked(String packageName) {
451 if (packageName == null) {
452 Log.e(TAG, "updatePackageParticipants called with null package name");
453 return;
454 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700455 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700456
457 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700458 List<ApplicationInfo> allApps = allAgentApps();
459 removePackageParticipantsLockedInner(packageName, allApps);
460 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700461 }
462
Christopher Tate6785dd82009-06-18 15:58:25 -0700463 private void backUpPackageManagerData() {
464 // No need to schedule a backup just for the metadata; just piggyback on
465 // the next actual data backup.
466 synchronized(this) {
467 mDoPackageManager = true;
468 }
469 }
470
471 // The queue lock should be held when scheduling a backup pass
472 private void scheduleBackupPassLocked(long timeFromNowMillis) {
473 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
474 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
475 }
476
Dan Egnor87a02bc2009-06-17 02:30:10 -0700477 // Return the given transport
478 private IBackupTransport getTransport(int transportID) {
Christopher Tate8c850b72009-06-07 19:33:20 -0700479 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700480 case BackupManager.TRANSPORT_LOCAL:
Christopher Tate6785dd82009-06-18 15:58:25 -0700481 Log.v(TAG, "Supplying local transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700482 return mLocalTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700483
484 case BackupManager.TRANSPORT_GOOGLE:
Christopher Tate6785dd82009-06-18 15:58:25 -0700485 Log.v(TAG, "Supplying Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700486 return mGoogleTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700487
488 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700489 Log.e(TAG, "Asked for unknown transport " + transportID);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700490 return null;
Christopher Tate8c850b72009-06-07 19:33:20 -0700491 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700492 }
493
Christopher Tatedf01dea2009-06-09 20:45:02 -0700494 // fire off a backup agent, blocking until it attaches or times out
495 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
496 IBackupAgent agent = null;
497 synchronized(mAgentConnectLock) {
498 mConnecting = true;
499 mConnectedAgent = null;
500 try {
501 if (mActivityManager.bindBackupAgent(app, mode)) {
502 Log.d(TAG, "awaiting agent for " + app);
503
504 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700505 // only wait 10 seconds for the clear data to happen
506 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
507 while (mConnecting && mConnectedAgent == null
508 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700509 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700510 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700511 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700512 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700513 return null;
514 }
515 }
516
517 // if we timed out with no connect, abort and move on
518 if (mConnecting == true) {
519 Log.w(TAG, "Timeout waiting for agent " + app);
520 return null;
521 }
522 agent = mConnectedAgent;
523 }
524 } catch (RemoteException e) {
525 // can't happen
526 }
527 }
528 return agent;
529 }
530
Christopher Tatec7b31e32009-06-10 15:49:30 -0700531 // clear an application's data, blocking until the operation completes or times out
532 void clearApplicationDataSynchronous(String packageName) {
533 ClearDataObserver observer = new ClearDataObserver();
534
535 synchronized(mClearDataLock) {
536 mClearingData = true;
537 mPackageManager.clearApplicationUserData(packageName, observer);
538
539 // only wait 10 seconds for the clear data to happen
540 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
541 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
542 try {
543 mClearDataLock.wait(5000);
544 } catch (InterruptedException e) {
545 // won't happen, but still.
546 mClearingData = false;
547 }
548 }
549 }
550 }
551
552 class ClearDataObserver extends IPackageDataObserver.Stub {
553 public void onRemoveCompleted(String packageName, boolean succeeded)
554 throws android.os.RemoteException {
555 synchronized(mClearDataLock) {
556 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700557 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700558 }
559 }
560 }
561
Christopher Tate043dadc2009-06-02 16:11:00 -0700562 // ----- Back up a set of applications via a worker thread -----
563
564 class PerformBackupThread extends Thread {
565 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700566 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700567 ArrayList<BackupRequest> mQueue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700568 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700569
Christopher Tateaa088442009-06-16 18:25:46 -0700570 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700571 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700572 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700573 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700574 mJournal = journal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700575 }
576
577 @Override
578 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700579 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
580
Christopher Tatedf01dea2009-06-09 20:45:02 -0700581 // start up the transport
582 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700583 mTransport.startSession();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700584 } catch (Exception e) {
585 Log.e(TAG, "Error session transport");
586 e.printStackTrace();
587 return;
588 }
589
Christopher Tate6785dd82009-06-18 15:58:25 -0700590 // The transport is up and running. First, back up the package manager
591 // metadata if necessary
592 boolean doPackageManager;
593 synchronized (BackupManagerService.this) {
594 doPackageManager = mDoPackageManager;
595 mDoPackageManager = false;
596 }
597 if (doPackageManager) {
598 // The package manager doesn't have a proper <application> etc, but since
599 // it's running here in the system process we can just set up its agent
600 // directly and use a synthetic BackupRequest.
601 if (DEBUG) Log.i(TAG, "Running PM backup pass as well");
602
603 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
604 mPackageManager, allAgentApps());
605 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
606 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
607 processOneBackup(pmRequest,
608 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
609 mTransport);
610 }
611
612 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700613 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700614
615 // Finally, tear down the transport
616 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700617 mTransport.endSession();
Christopher Tate043dadc2009-06-02 16:11:00 -0700618 } catch (Exception e) {
619 Log.e(TAG, "Error ending transport");
620 e.printStackTrace();
621 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700622
623 if (!mJournal.delete()) {
624 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
625 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700626 }
627
628 private void doQueuedBackups(IBackupTransport transport) {
629 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700630 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700631
632 IBackupAgent agent = null;
633 int mode = (request.fullBackup)
634 ? IApplicationThread.BACKUP_MODE_FULL
635 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
636 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700637 agent = bindToAgentSynchronous(request.appInfo, mode);
638 if (agent != null) {
639 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700640 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700641
642 // unbind even on timeout, just in case
643 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700644 } catch (SecurityException ex) {
645 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700646 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700647 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700648 Log.v(TAG, "bind/backup threw");
649 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700650 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700651
Christopher Tate043dadc2009-06-02 16:11:00 -0700652 }
653 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700654
655 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
656 final String packageName = request.appInfo.packageName;
657 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
658
659 try {
660 // Look up the package info & signatures. This is first so that if it
661 // throws an exception, there's no file setup yet that would need to
662 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700663 PackageInfo packInfo;
664 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
665 // The metadata 'package' is synthetic
666 packInfo = new PackageInfo();
667 packInfo.packageName = packageName;
668 } else {
669 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700670 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700671 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700672
673 // !!! TODO: get the state file dir from the transport
674 File savedStateName = new File(mStateDir, packageName);
675 File backupDataName = new File(mDataDir, packageName + ".data");
676 File newStateName = new File(mStateDir, packageName + ".new");
677
678 // In a full backup, we pass a null ParcelFileDescriptor as
679 // the saved-state "file"
680 ParcelFileDescriptor savedState = (request.fullBackup) ? null
681 : ParcelFileDescriptor.open(savedStateName,
682 ParcelFileDescriptor.MODE_READ_ONLY |
683 ParcelFileDescriptor.MODE_CREATE);
684
685 backupDataName.delete();
686 ParcelFileDescriptor backupData =
687 ParcelFileDescriptor.open(backupDataName,
688 ParcelFileDescriptor.MODE_READ_WRITE |
689 ParcelFileDescriptor.MODE_CREATE);
690
691 newStateName.delete();
692 ParcelFileDescriptor newState =
693 ParcelFileDescriptor.open(newStateName,
694 ParcelFileDescriptor.MODE_READ_WRITE |
695 ParcelFileDescriptor.MODE_CREATE);
696
697 // Run the target's backup pass
698 boolean success = false;
699 try {
700 agent.doBackup(savedState, backupData, newState);
701 success = true;
702 } finally {
703 if (savedState != null) {
704 savedState.close();
705 }
706 backupData.close();
707 newState.close();
708 }
709
710 // Now propagate the newly-backed-up data to the transport
711 if (success) {
712 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
713 backupData =
714 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
715 int error = transport.performBackup(packInfo, backupData);
716
717 // !!! TODO: After successful transport, delete the now-stale data
718 // and juggle the files so that next time the new state is passed
719 //backupDataName.delete();
720 newStateName.renameTo(savedStateName);
721 }
722 } catch (NameNotFoundException e) {
723 Log.e(TAG, "Package not found on backup: " + packageName);
724 } catch (FileNotFoundException fnf) {
725 Log.w(TAG, "File not found on backup: ");
726 fnf.printStackTrace();
727 } catch (RemoteException e) {
728 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
729 e.printStackTrace();
730 } catch (Exception e) {
731 Log.w(TAG, "Final exception guard in backup: ");
732 e.printStackTrace();
733 }
734 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700735 }
736
Christopher Tatedf01dea2009-06-09 20:45:02 -0700737
738 // ----- Restore handling -----
739
740 // Is the given package restorable on this device? Returns the on-device app's
741 // ApplicationInfo struct if it is; null if not.
742 //
743 // !!! TODO: also consider signatures
Christopher Tatec7b31e32009-06-10 15:49:30 -0700744 PackageInfo isRestorable(PackageInfo packageInfo) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700745 if (packageInfo.packageName != null) {
746 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700747 PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
Christopher Tatedf01dea2009-06-09 20:45:02 -0700748 PackageManager.GET_SIGNATURES);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700749 if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700750 return app;
751 }
752 } catch (Exception e) {
753 // doesn't exist on this device, or other error -- just ignore it.
754 }
755 }
756 return null;
757 }
758
Christopher Tateabce4e82009-06-18 18:35:32 -0700759 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700760 // Allow unsigned apps, but not signed on one device and unsigned on the other
761 // !!! TODO: is this the right policy?
762 if ((storedSigs == null || storedSigs.length == 0)
763 && (deviceSigs == null || deviceSigs.length == 0)) {
764 return true;
765 }
766 if (storedSigs == null || deviceSigs == null) {
767 return false;
768 }
769
Christopher Tateabce4e82009-06-18 18:35:32 -0700770 // !!! TODO: this demands that every stored signature match one
771 // that is present on device, and does not demand the converse.
772 // Is this this right policy?
773 int nStored = storedSigs.length;
774 int nDevice = deviceSigs.length;
775
776 for (int i=0; i < nStored; i++) {
777 boolean match = false;
778 for (int j=0; j < nDevice; j++) {
779 if (storedSigs[i].equals(deviceSigs[j])) {
780 match = true;
781 break;
782 }
783 }
784 if (!match) {
785 return false;
786 }
787 }
788 return true;
789 }
790
Christopher Tatedf01dea2009-06-09 20:45:02 -0700791 class PerformRestoreThread extends Thread {
792 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700793 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700794 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700795
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700796 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700797 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700798 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700799 }
800
801 @Override
802 public void run() {
803 /**
804 * Restore sequence:
805 *
806 * 1. start up the transport session
807 * 2. get the restore set description for our identity
808 * 3. for each app in the restore set:
809 * 3.a. if it's restorable on this device, add it to the restore queue
810 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700811 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700812 * 4.b. get the restore data for the app from the transport
813 * 4.c. launch the backup agent for the app
814 * 4.d. agent.doRestore() with the data from the server
815 * 4.e. unbind the agent [and kill the app?]
816 * 5. shut down the transport
817 */
818
819 int err = -1;
820 try {
821 err = mTransport.startSession();
822 } catch (Exception e) {
823 Log.e(TAG, "Error starting transport for restore");
824 e.printStackTrace();
825 }
826
827 if (err == 0) {
828 // build the set of apps to restore
829 try {
830 RestoreSet[] images = mTransport.getAvailableRestoreSets();
831 if (images.length > 0) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700832 // !!! TODO: pick out the set for this token
Christopher Tatec7b31e32009-06-10 15:49:30 -0700833 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700834
Christopher Tateabce4e82009-06-18 18:35:32 -0700835 // Pull the Package Manager metadata from the restore set first
836 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
837 mPackageManager, allAgentApps());
838 PackageInfo pmApp = new PackageInfo();
839 pmApp.packageName = PACKAGE_MANAGER_SENTINEL;
840 processOneRestore(pmApp, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
841
Christopher Tatedf01dea2009-06-09 20:45:02 -0700842 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700843 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
844 HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700845 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700846 // get the real PackageManager idea of the package
847 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700848 if (app != null) {
Christopher Tateabce4e82009-06-18 18:35:32 -0700849 // Validate against the backed-up signature block, too
850 Signature[] storedSigs
851 = pmAgent.getRestoredSignatures(app.packageName);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700852 // !!! TODO: check app version here as well
853 if (signaturesMatch(storedSigs, app.signatures)) {
854 appsToRestore.add(app);
Christopher Tateabce4e82009-06-18 18:35:32 -0700855 } else {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700856 Log.w(TAG, "Sig mismatch on restore of " + app.packageName);
Christopher Tateabce4e82009-06-18 18:35:32 -0700857 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700858 }
859 }
860
861 // now run the restore queue
862 doQueuedRestores(appsToRestore);
863 }
864 } catch (RemoteException e) {
865 // can't happen; transports run locally
866 }
867
868 // done; shut down the transport
869 try {
870 mTransport.endSession();
871 } catch (Exception e) {
872 Log.e(TAG, "Error ending transport for restore");
873 e.printStackTrace();
874 }
875 }
876
877 // even if the initial session startup failed, report that we're done here
878 }
879
880 // restore each app in the queue
Christopher Tatec7b31e32009-06-10 15:49:30 -0700881 void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
882 for (PackageInfo app : appsToRestore) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700883 Log.d(TAG, "starting agent for restore of " + app);
884
Christopher Tatedf01dea2009-06-09 20:45:02 -0700885 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700886 // Remove the app's data first
887 clearApplicationDataSynchronous(app.packageName);
888
889 // Now perform the restore into the clean app
890 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
891 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700892 if (agent != null) {
893 processOneRestore(app, agent);
894 }
895
896 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700897 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700898 } catch (SecurityException ex) {
899 // Try for the next one.
900 Log.d(TAG, "error in bind", ex);
901 } catch (RemoteException e) {
902 // can't happen
903 }
904
905 }
906 }
907
Christopher Tatec7b31e32009-06-10 15:49:30 -0700908 // Do the guts of a restore of one application, derived from the 'mImage'
909 // restore set via the 'mTransport' transport.
910 void processOneRestore(PackageInfo app, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700911 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700912 final String packageName = app.packageName;
913
914 // !!! TODO: get the dirs from the transport
915 File backupDataName = new File(mDataDir, packageName + ".restore");
916 backupDataName.delete();
917 try {
918 ParcelFileDescriptor backupData =
919 ParcelFileDescriptor.open(backupDataName,
920 ParcelFileDescriptor.MODE_READ_WRITE |
921 ParcelFileDescriptor.MODE_CREATE);
922
923 // Run the transport's restore pass
924 // Run the target's backup pass
925 int err = -1;
926 try {
927 err = mTransport.getRestoreData(mImage.token, app, backupData);
928 } catch (RemoteException e) {
929 // can't happen
930 } finally {
931 backupData.close();
932 }
933
934 // Okay, we have the data. Now have the agent do the restore.
935 File newStateName = new File(mStateDir, packageName + ".new");
936 ParcelFileDescriptor newState =
937 ParcelFileDescriptor.open(newStateName,
938 ParcelFileDescriptor.MODE_READ_WRITE |
939 ParcelFileDescriptor.MODE_CREATE);
940
941 backupData = ParcelFileDescriptor.open(backupDataName,
942 ParcelFileDescriptor.MODE_READ_ONLY);
943
944 boolean success = false;
945 try {
946 agent.doRestore(backupData, newState);
947 success = true;
948 } catch (Exception e) {
949 Log.e(TAG, "Restore failed for " + packageName);
950 e.printStackTrace();
951 } finally {
952 newState.close();
953 backupData.close();
954 }
955
956 // if everything went okay, remember the recorded state now
957 if (success) {
958 File savedStateName = new File(mStateDir, packageName);
959 newStateName.renameTo(savedStateName);
960 }
961 } catch (FileNotFoundException fnfe) {
962 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
963 } catch (IOException ioe) {
964 Log.e(TAG, "Unable to process restore file: " + ioe);
965 } catch (Exception e) {
966 Log.e(TAG, "Final exception guard in restore:");
967 e.printStackTrace();
968 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700969 }
970 }
971
972
Christopher Tate487529a2009-04-29 14:03:25 -0700973 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700974
Christopher Tatea8bf8152009-04-30 11:36:21 -0700975 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700976 // Record that we need a backup pass for the caller. Since multiple callers
977 // may share a uid, we need to note all candidates within that uid and schedule
978 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700979
980 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700981
982 // If the caller does not hold the BACKUP permission, it can only request a
983 // backup of its own data.
984 HashSet<ApplicationInfo> targets;
985 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
986 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
987 targets = mBackupParticipants.get(Binder.getCallingUid());
988 } else {
989 // a caller with full permission can ask to back up any participating app
990 // !!! TODO: allow backup of ANY app?
991 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
992 targets = new HashSet<ApplicationInfo>();
993 int N = mBackupParticipants.size();
994 for (int i = 0; i < N; i++) {
995 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
996 if (s != null) {
997 targets.addAll(s);
998 }
999 }
1000 }
Christopher Tate487529a2009-04-29 14:03:25 -07001001 if (targets != null) {
1002 synchronized (mQueueLock) {
1003 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001004 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001005 // validate the caller-supplied package name against the known set of
1006 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001007 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001008 // Add the caller to the set of pending backups. If there is
1009 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001010 BackupRequest req = new BackupRequest(app, false);
1011 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001012
1013 // Journal this request in case of crash
1014 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001015 }
1016 }
1017
Christopher Tate181fafa2009-05-14 11:12:14 -07001018 if (DEBUG) {
1019 int numKeys = mPendingBackups.size();
1020 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1021 for (BackupRequest b : mPendingBackups.values()) {
1022 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1023 }
1024 }
Christopher Tate487529a2009-04-29 14:03:25 -07001025 // Schedule a backup pass in a few minutes. As backup-eligible data
1026 // keeps changing, continue to defer the backup pass until things
1027 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001028 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001029 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001030 } else {
1031 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001032 }
1033 }
Christopher Tate46758122009-05-06 11:22:00 -07001034
Christopher Tatecde87f42009-06-12 12:55:53 -07001035 private void writeToJournalLocked(String str) {
1036 if (mJournalStream != null) {
1037 try {
1038 mJournalStream.writeUTF(str);
1039 } catch (IOException e) {
1040 Log.e(TAG, "Error writing to backup journal");
1041 mJournalStream = null;
1042 mJournal = null;
1043 }
1044 }
1045 }
1046
Christopher Tateace7f092009-06-15 18:07:25 -07001047 // Run a backup pass immediately for any applications that have declared
1048 // that they have pending updates.
1049 public void backupNow() throws RemoteException {
1050 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001051
Christopher Tateace7f092009-06-15 18:07:25 -07001052 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001053 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001054 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001055 }
1056 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001057
Christopher Tateace7f092009-06-15 18:07:25 -07001058 // Report the currently active transport
1059 public int getCurrentTransport() {
1060 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001061 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001062 return mTransportId;
1063 }
1064
Christopher Tate043dadc2009-06-02 16:11:00 -07001065 // Select which transport to use for the next backup operation
1066 public int selectBackupTransport(int transportId) {
1067 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1068
Dan Egnor87a02bc2009-06-17 02:30:10 -07001069 int prevTransport = mTransportId;
1070 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001071 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001072 return prevTransport;
1073 }
1074
1075 // Callback: a requested backup agent has been instantiated. This should only
1076 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001077 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001078 synchronized(mAgentConnectLock) {
1079 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1080 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1081 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1082 mConnectedAgent = agent;
1083 mConnecting = false;
1084 } else {
1085 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1086 + " claiming agent connected");
1087 }
1088 mAgentConnectLock.notifyAll();
1089 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001090 }
1091
1092 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1093 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001094 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001095 public void agentDisconnected(String packageName) {
1096 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001097 synchronized(mAgentConnectLock) {
1098 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1099 mConnectedAgent = null;
1100 mConnecting = false;
1101 } else {
1102 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1103 + " claiming agent disconnected");
1104 }
1105 mAgentConnectLock.notifyAll();
1106 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001107 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001108
Christopher Tate8c850b72009-06-07 19:33:20 -07001109 // Hand off a restore session
1110 public IRestoreSession beginRestoreSession(int transportID) {
1111 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001112
1113 synchronized(this) {
1114 if (mActiveRestoreSession != null) {
1115 Log.d(TAG, "Restore session requested but one already active");
1116 return null;
1117 }
1118 mActiveRestoreSession = new RestoreSession(transportID);
1119 }
1120 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001121 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001122
Christopher Tate9b3905c2009-06-08 15:24:01 -07001123 // ----- Restore session -----
1124
1125 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001126 private static final String TAG = "RestoreSession";
1127
Christopher Tate9b3905c2009-06-08 15:24:01 -07001128 private IBackupTransport mRestoreTransport = null;
1129 RestoreSet[] mRestoreSets = null;
1130
1131 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001132 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001133 }
1134
1135 // --- Binder interface ---
1136 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001137 mContext.enforceCallingPermission("android.permission.BACKUP",
1138 "getAvailableRestoreSets");
1139
Christopher Tatef68eb502009-06-16 11:02:01 -07001140 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001141 synchronized(this) {
1142 if (mRestoreSets == null) {
1143 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1144 }
1145 return mRestoreSets;
1146 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001147 } catch (RuntimeException e) {
1148 Log.d(TAG, "getAvailableRestoreSets exception");
1149 e.printStackTrace();
1150 throw e;
1151 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001152 }
1153
1154 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001155 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1156
1157 if (mRestoreSets != null) {
1158 for (int i = 0; i < mRestoreSets.length; i++) {
1159 if (token == mRestoreSets[i].token) {
1160 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1161 mRestoreTransport);
1162 msg.arg1 = token;
1163 mBackupHandler.sendMessage(msg);
1164 return 0;
1165 }
1166 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001167 } else {
1168 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001169 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001170 return -1;
1171 }
1172
1173 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001174 mContext.enforceCallingPermission("android.permission.BACKUP",
1175 "endRestoreSession");
1176
Christopher Tate9b3905c2009-06-08 15:24:01 -07001177 mRestoreTransport.endSession();
1178 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001179 synchronized(BackupManagerService.this) {
1180 if (BackupManagerService.this.mActiveRestoreSession == this) {
1181 BackupManagerService.this.mActiveRestoreSession = null;
1182 } else {
1183 Log.e(TAG, "ending non-current restore session");
1184 }
1185 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001186 }
1187 }
1188
Christopher Tate043dadc2009-06-02 16:11:00 -07001189
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001190 @Override
1191 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1192 synchronized (mQueueLock) {
1193 int N = mBackupParticipants.size();
1194 pw.println("Participants:");
1195 for (int i=0; i<N; i++) {
1196 int uid = mBackupParticipants.keyAt(i);
1197 pw.print(" uid: ");
1198 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001199 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1200 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001201 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001202 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001203 }
1204 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001205 pw.println("Pending:");
1206 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
1207 while (br.hasNext()) {
1208 pw.print(" ");
1209 pw.println(br);
1210 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001211 }
1212 }
Christopher Tate487529a2009-04-29 14:03:25 -07001213}