blob: 8297aa210ac132f494f47268c39fcdb2f7c34251 [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 Tate7d562ec2009-06-25 18:03:43 -070049import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070050import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070051import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070052import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070053
Christopher Tate9bbc21a2009-06-10 20:23:25 -070054import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070055import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070056
Christopher Tate6785dd82009-06-18 15:58:25 -070057import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070058import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070059
Christopher Tatecde87f42009-06-12 12:55:53 -070060import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070061import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070062import java.io.FileDescriptor;
Christopher Tatec7b31e32009-06-10 15:49:30 -070063import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070064import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070065import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070066import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040067import java.util.ArrayList;
68import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070069import java.util.HashSet;
70import 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
Christopher Tate111bd4a2009-06-24 17:29:38 -070077 private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070078
79 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070080 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070081 private static final int MSG_RUN_RESTORE = 3;
Christopher Tate7d562ec2009-06-25 18:03:43 -070082 private static final String RESTORE_OBSERVER_KEY = "_resOb";
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 Tate5cb400b2009-06-25 16:03:14 -0700111
112 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate6785dd82009-06-18 15:58:25 -0700113 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700114
115 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700116 private final Object mQueueLock = new Object();
117
Christopher Tate043dadc2009-06-02 16:11:00 -0700118 // The thread performing the sequence of queued backups binds to each app's agent
119 // in succession. Bind notifications are asynchronously delivered through the
120 // Activity Manager; use this lock object to signal when a requested binding has
121 // completed.
122 private final Object mAgentConnectLock = new Object();
123 private IBackupAgent mConnectedAgent;
124 private volatile boolean mConnecting;
125
Christopher Tatec7b31e32009-06-10 15:49:30 -0700126 // A similar synchronicity mechanism around clearing apps' data for restore
127 private final Object mClearDataLock = new Object();
128 private volatile boolean mClearingData;
129
Christopher Tateaa088442009-06-16 18:25:46 -0700130 // Current active transport & restore session
Christopher Tate043dadc2009-06-02 16:11:00 -0700131 private int mTransportId;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700132 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700133 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700134
Christopher Tate7d562ec2009-06-25 18:03:43 -0700135 private class RestoreParams {
136 public IBackupTransport transport;
137 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700138 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700139
Dan Egnor156411d2009-06-26 13:20:02 -0700140 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700141 transport = _transport;
142 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700143 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700144 }
145 }
146
Christopher Tate5cb400b2009-06-25 16:03:14 -0700147 // Where we keep our journal files and other bookkeeping
148 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700149 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700150 private File mJournalDir;
151 private File mJournal;
152 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700153
Christopher Tate487529a2009-04-29 14:03:25 -0700154 public BackupManagerService(Context context) {
155 mContext = context;
156 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700157 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700158
Christopher Tate22b87872009-05-04 16:41:53 -0700159 // Set up our bookkeeping
Christopher Tate5cb400b2009-06-25 16:03:14 -0700160 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700161 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700162
Christopher Tatecde87f42009-06-12 12:55:53 -0700163 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700164 mJournalDir = new File(mBaseStateDir, "pending");
165 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700166 makeJournalLocked(); // okay because no other threads are running yet
167
Christopher Tateabce4e82009-06-18 18:35:32 -0700168 // Build our mapping of uid to backup client services. This implicitly
169 // schedules a backup pass on the Package Manager metadata the first
170 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700171 synchronized (mBackupParticipants) {
172 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700173 }
174
Dan Egnor87a02bc2009-06-17 02:30:10 -0700175 // Set up our transport options and initialize the default transport
176 // TODO: Have transports register themselves somehow?
177 // TODO: Don't create transports that we don't need to?
Dan Egnor6f211282009-06-25 09:28:29 -0700178 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700179 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
180 mGoogleTransport = null;
181
182 // Attach to the Google backup transport.
183 Intent intent = new Intent().setComponent(new ComponentName(
184 "com.google.android.backup",
185 "com.google.android.backup.BackupTransportService"));
186 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700187
Christopher Tatecde87f42009-06-12 12:55:53 -0700188 // Now that we know about valid backup participants, parse any
189 // leftover journal files and schedule a new backup pass
190 parseLeftoverJournals();
191
Christopher Tate3799bc22009-05-06 16:13:56 -0700192 // Register for broadcasts about package install, etc., so we can
193 // update the provider list.
194 IntentFilter filter = new IntentFilter();
195 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
196 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
197 filter.addDataScheme("package");
198 mContext.registerReceiver(mBroadcastReceiver, filter);
199 }
200
Christopher Tatecde87f42009-06-12 12:55:53 -0700201 private void makeJournalLocked() {
202 try {
203 mJournal = File.createTempFile("journal", null, mJournalDir);
204 mJournalStream = new RandomAccessFile(mJournal, "rwd");
205 } catch (IOException e) {
206 Log.e(TAG, "Unable to write backup journals");
207 mJournal = null;
208 mJournalStream = null;
209 }
210 }
211
212 private void parseLeftoverJournals() {
213 if (mJournal != null) {
214 File[] allJournals = mJournalDir.listFiles();
215 for (File f : allJournals) {
216 if (f.compareTo(mJournal) != 0) {
217 // This isn't the current journal, so it must be a leftover. Read
218 // out the package names mentioned there and schedule them for
219 // backup.
220 try {
221 Log.i(TAG, "Found stale backup journal, scheduling:");
222 RandomAccessFile in = new RandomAccessFile(f, "r");
223 while (true) {
224 String packageName = in.readUTF();
225 Log.i(TAG, " + " + packageName);
226 dataChanged(packageName);
227 }
228 } catch (EOFException e) {
229 // no more data; we're done
230 } catch (Exception e) {
231 // can't read it or other error; just skip it
232 } finally {
233 // close/delete the file
234 f.delete();
235 }
236 }
237 }
238 }
239 }
240
Christopher Tate3799bc22009-05-06 16:13:56 -0700241 // ----- Track installation/removal of packages -----
242 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
243 public void onReceive(Context context, Intent intent) {
244 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
245
246 Uri uri = intent.getData();
247 if (uri == null) {
248 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700249 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700250 String pkgName = uri.getSchemeSpecificPart();
251 if (pkgName == null) {
252 return;
253 }
254
255 String action = intent.getAction();
256 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
257 synchronized (mBackupParticipants) {
258 Bundle extras = intent.getExtras();
259 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
260 // The package was just upgraded
261 updatePackageParticipantsLocked(pkgName);
262 } else {
263 // The package was just added
264 addPackageParticipantsLocked(pkgName);
265 }
266 }
267 }
268 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
269 Bundle extras = intent.getExtras();
270 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
271 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
272 } else {
273 synchronized (mBackupParticipants) {
274 removePackageParticipantsLocked(pkgName);
275 }
276 }
277 }
278 }
279 };
280
Dan Egnor87a02bc2009-06-17 02:30:10 -0700281 // ----- Track connection to GoogleBackupTransport service -----
282 ServiceConnection mGoogleConnection = new ServiceConnection() {
283 public void onServiceConnected(ComponentName name, IBinder service) {
284 if (DEBUG) Log.v(TAG, "Connected to Google transport");
285 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
286 }
287
288 public void onServiceDisconnected(ComponentName name) {
289 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
290 mGoogleTransport = null;
291 }
292 };
293
Joe Onorato8ad02812009-05-13 01:41:44 -0400294 // ----- Run the actual backup process asynchronously -----
295
Christopher Tate181fafa2009-05-14 11:12:14 -0700296 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400297 public void handleMessage(Message msg) {
298
299 switch (msg.what) {
300 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700301 {
302 IBackupTransport transport = getTransport(mTransportId);
303 if (transport == null) {
304 Log.v(TAG, "Backup requested but no transport available");
305 break;
306 }
307
Joe Onorato8ad02812009-05-13 01:41:44 -0400308 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700309 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700310 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400311 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700312 if (mPendingBackups.size() == 0) {
313 Log.v(TAG, "Backup requested but nothing pending");
314 break;
315 }
316
Christopher Tate6aa41f42009-06-19 14:14:22 -0700317 for (BackupRequest b: mPendingBackups.values()) {
318 queue.add(b);
Joe Onorato8ad02812009-05-13 01:41:44 -0400319 }
Christopher Tate6aa41f42009-06-19 14:14:22 -0700320 Log.v(TAG, "clearing pending backups");
321 mPendingBackups.clear();
Christopher Tateace7f092009-06-15 18:07:25 -0700322
323 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700324 if (mJournalStream != null) {
325 try {
326 mJournalStream.close();
327 } catch (IOException e) {
328 // don't need to do anything
329 }
330 makeJournalLocked();
331 }
332
333 // At this point, we have started a new journal file, and the old
334 // file identity is being passed to the backup processing thread.
335 // When it completes successfully, that old journal file will be
336 // deleted. If we crash prior to that, the old journal is parsed
337 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400338 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700339
Christopher Tate6aa41f42009-06-19 14:14:22 -0700340 (new PerformBackupThread(transport, queue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700341 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700342 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700343
344 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400345 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700346
347 case MSG_RUN_RESTORE:
348 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700349 RestoreParams params = (RestoreParams)msg.obj;
Dan Egnor156411d2009-06-26 13:20:02 -0700350 (new PerformRestoreThread(params.transport, params.observer, params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700351 break;
352 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400353 }
354 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400355 }
356
Christopher Tate181fafa2009-05-14 11:12:14 -0700357 // Add the backup agents in the given package to our set of known backup participants.
358 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700359 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700360 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700361 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700362 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700363 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700364 }
365
Christopher Tate181fafa2009-05-14 11:12:14 -0700366 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700367 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700368 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700369 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
370 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700371 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
372 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700373 }
374 }
375
Dan Egnorefe52642009-06-24 00:16:33 -0700376 for (PackageInfo pkg : targetPkgs) {
377 if (packageName == null || pkg.packageName.equals(packageName)) {
378 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700379 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700380 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700381 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700382 mBackupParticipants.put(uid, set);
383 }
Dan Egnorefe52642009-06-24 00:16:33 -0700384 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700385 }
Christopher Tate487529a2009-04-29 14:03:25 -0700386 }
387 }
388
Christopher Tate6785dd82009-06-18 15:58:25 -0700389 // Remove the given package's entry from our known active set. If
390 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700391 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700392 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700393 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700394 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700395 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700396 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700397 int flags = PackageManager.GET_SIGNATURES;
398 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700399 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700400 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700401 }
402 } else {
403 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700404 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700405 }
406 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700407 }
408
Joe Onorato8ad02812009-05-13 01:41:44 -0400409 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700410 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700411 if (DEBUG) {
412 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
413 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700414 for (PackageInfo p : agents) {
415 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700416 }
417 }
Dan Egnorefe52642009-06-24 00:16:33 -0700418 for (PackageInfo pkg : agents) {
419 if (packageName == null || pkg.packageName.equals(packageName)) {
420 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700421 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700422 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700423 // Find the existing entry with the same package name, and remove it.
424 // We can't just remove(app) because the instances are different.
425 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700426 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700427 set.remove(entry);
428 break;
429 }
430 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700431 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700432 mBackupParticipants.delete(uid);
433 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700434 }
435 }
436 }
437 }
438
Christopher Tate181fafa2009-05-14 11:12:14 -0700439 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700440 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700441 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700442 int flags = PackageManager.GET_SIGNATURES;
443 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
444 int N = packages.size();
445 for (int a = N-1; a >= 0; a--) {
446 ApplicationInfo app = packages.get(a).applicationInfo;
447 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
448 || app.backupAgentName == null) {
449 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700450 }
451 }
Dan Egnorefe52642009-06-24 00:16:33 -0700452 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700453 }
Christopher Tateaa088442009-06-16 18:25:46 -0700454
Christopher Tate3799bc22009-05-06 16:13:56 -0700455 // Reset the given package's known backup participants. Unlike add/remove, the update
456 // action cannot be passed a null package name.
457 void updatePackageParticipantsLocked(String packageName) {
458 if (packageName == null) {
459 Log.e(TAG, "updatePackageParticipants called with null package name");
460 return;
461 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700462 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700463
464 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700465 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700466 removePackageParticipantsLockedInner(packageName, allApps);
467 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700468 }
469
Christopher Tate6785dd82009-06-18 15:58:25 -0700470 // 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 Tate5cb400b2009-06-25 16:03:14 -0700567 File mStateDir;
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 Tate5cb400b2009-06-25 16:03:14 -0700575
576 try {
577 mStateDir = new File(mBaseStateDir, transport.transportDirName());
578 } catch (RemoteException e) {
579 // can't happen; the transport is local
580 }
581 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700582 }
583
584 @Override
585 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700586 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
587
Christopher Tate5cb400b2009-06-25 16:03:14 -0700588 // The package manager doesn't have a proper <application> etc, but since
589 // it's running here in the system process we can just set up its agent
590 // directly and use a synthetic BackupRequest. We always run this pass
591 // because it's cheap and this way we guarantee that we don't get out of
592 // step even if we're selecting among various transports at run time.
593 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
594 mPackageManager, allAgentPackages());
595 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
596 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
597 processOneBackup(pmRequest,
598 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
599 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700600
601 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700602 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700603
604 // Finally, tear down the transport
605 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700606 if (!mTransport.finishBackup()) {
607 // STOPSHIP TODO: handle errors
608 Log.e(TAG, "Backup failure in finishBackup()");
609 }
610 } catch (RemoteException e) {
611 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700612 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700613
614 if (!mJournal.delete()) {
615 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
616 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700617 }
618
619 private void doQueuedBackups(IBackupTransport transport) {
620 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700621 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700622
623 IBackupAgent agent = null;
624 int mode = (request.fullBackup)
625 ? IApplicationThread.BACKUP_MODE_FULL
626 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
627 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700628 agent = bindToAgentSynchronous(request.appInfo, mode);
629 if (agent != null) {
630 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700631 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700632
633 // unbind even on timeout, just in case
634 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700635 } catch (SecurityException ex) {
636 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700637 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700638 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700639 Log.v(TAG, "bind/backup threw");
640 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700641 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700642
Christopher Tate043dadc2009-06-02 16:11:00 -0700643 }
644 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700645
646 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
647 final String packageName = request.appInfo.packageName;
648 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
649
650 try {
651 // Look up the package info & signatures. This is first so that if it
652 // throws an exception, there's no file setup yet that would need to
653 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700654 PackageInfo packInfo;
655 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
656 // The metadata 'package' is synthetic
657 packInfo = new PackageInfo();
658 packInfo.packageName = packageName;
659 } else {
660 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700661 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700662 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700663
664 // !!! TODO: get the state file dir from the transport
665 File savedStateName = new File(mStateDir, packageName);
666 File backupDataName = new File(mDataDir, packageName + ".data");
667 File newStateName = new File(mStateDir, packageName + ".new");
668
669 // In a full backup, we pass a null ParcelFileDescriptor as
670 // the saved-state "file"
671 ParcelFileDescriptor savedState = (request.fullBackup) ? null
672 : ParcelFileDescriptor.open(savedStateName,
673 ParcelFileDescriptor.MODE_READ_ONLY |
674 ParcelFileDescriptor.MODE_CREATE);
675
676 backupDataName.delete();
677 ParcelFileDescriptor backupData =
678 ParcelFileDescriptor.open(backupDataName,
679 ParcelFileDescriptor.MODE_READ_WRITE |
680 ParcelFileDescriptor.MODE_CREATE);
681
682 newStateName.delete();
683 ParcelFileDescriptor newState =
684 ParcelFileDescriptor.open(newStateName,
685 ParcelFileDescriptor.MODE_READ_WRITE |
686 ParcelFileDescriptor.MODE_CREATE);
687
688 // Run the target's backup pass
689 boolean success = false;
690 try {
691 agent.doBackup(savedState, backupData, newState);
692 success = true;
693 } finally {
694 if (savedState != null) {
695 savedState.close();
696 }
697 backupData.close();
698 newState.close();
699 }
700
701 // Now propagate the newly-backed-up data to the transport
702 if (success) {
703 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
704 backupData =
705 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700706 if (!transport.performBackup(packInfo, backupData)) {
707 // STOPSHIP TODO: handle errors
708 Log.e(TAG, "Backup failure in performBackup()");
709 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700710
711 // !!! TODO: After successful transport, delete the now-stale data
712 // and juggle the files so that next time the new state is passed
713 //backupDataName.delete();
714 newStateName.renameTo(savedStateName);
715 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700716 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700717 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700718 }
719 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700720 }
721
Christopher Tatedf01dea2009-06-09 20:45:02 -0700722
723 // ----- Restore handling -----
724
Christopher Tateabce4e82009-06-18 18:35:32 -0700725 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700726 // Allow unsigned apps, but not signed on one device and unsigned on the other
727 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700728 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
729 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700730 if ((storedSigs == null || storedSigs.length == 0)
731 && (deviceSigs == null || deviceSigs.length == 0)) {
732 return true;
733 }
734 if (storedSigs == null || deviceSigs == null) {
735 return false;
736 }
737
Christopher Tateabce4e82009-06-18 18:35:32 -0700738 // !!! TODO: this demands that every stored signature match one
739 // that is present on device, and does not demand the converse.
740 // Is this this right policy?
741 int nStored = storedSigs.length;
742 int nDevice = deviceSigs.length;
743
744 for (int i=0; i < nStored; i++) {
745 boolean match = false;
746 for (int j=0; j < nDevice; j++) {
747 if (storedSigs[i].equals(deviceSigs[j])) {
748 match = true;
749 break;
750 }
751 }
752 if (!match) {
753 return false;
754 }
755 }
756 return true;
757 }
758
Christopher Tatedf01dea2009-06-09 20:45:02 -0700759 class PerformRestoreThread extends Thread {
760 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700761 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700762 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700763 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700764 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700765
Christopher Tate5cbbf562009-06-22 16:44:51 -0700766 class RestoreRequest {
767 public PackageInfo app;
768 public int storedAppVersion;
769
770 RestoreRequest(PackageInfo _app, int _version) {
771 app = _app;
772 storedAppVersion = _version;
773 }
774 }
775
Christopher Tate7d562ec2009-06-25 18:03:43 -0700776 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700777 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700778 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700779 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700780 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700781
782 try {
783 mStateDir = new File(mBaseStateDir, transport.transportDirName());
784 } catch (RemoteException e) {
785 // can't happen; the transport is local
786 }
787 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700788 }
789
790 @Override
791 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700792 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700793 /**
794 * Restore sequence:
795 *
Dan Egnorefe52642009-06-24 00:16:33 -0700796 * 1. get the restore set description for our identity
797 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700798 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700799 * 3. for each app in the restore queue:
800 * 3.a. clear the app data
801 * 3.b. get the restore data for the app from the transport
802 * 3.c. launch the backup agent for the app
803 * 3.d. agent.doRestore() with the data from the server
804 * 3.e. unbind the agent [and kill the app?]
805 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700806 */
807
Christopher Tate7d562ec2009-06-25 18:03:43 -0700808 int error = -1; // assume error
809
Dan Egnorefe52642009-06-24 00:16:33 -0700810 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700811 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700812 RestoreSet[] images = mTransport.getAvailableRestoreSets();
813 if (images == null) {
814 // STOPSHIP TODO: Handle the failure somehow?
815 Log.e(TAG, "Error getting restore sets");
816 return;
817 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700818
Dan Egnorefe52642009-06-24 00:16:33 -0700819 if (images.length == 0) {
820 Log.i(TAG, "No restore sets available");
821 return;
822 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700823
Dan Egnorefe52642009-06-24 00:16:33 -0700824 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700825
Dan Egnorefe52642009-06-24 00:16:33 -0700826 // Get the list of all packages which have backup enabled.
827 // (Include the Package Manager metadata pseudo-package first.)
828 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
829 PackageInfo omPackage = new PackageInfo();
830 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
831 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700832
Dan Egnorefe52642009-06-24 00:16:33 -0700833 List<PackageInfo> agentPackages = allAgentPackages();
834 restorePackages.addAll(agentPackages);
835
Christopher Tate7d562ec2009-06-25 18:03:43 -0700836 // let the observer know that we're running
837 if (mObserver != null) {
838 try {
839 // !!! TODO: get an actual count from the transport after
840 // its startRestore() runs?
841 mObserver.restoreStarting(restorePackages.size());
842 } catch (RemoteException e) {
843 Log.d(TAG, "Restore observer died at restoreStarting");
844 mObserver = null;
845 }
846 }
847
Dan Egnor156411d2009-06-26 13:20:02 -0700848 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700849 // STOPSHIP TODO: Handle the failure somehow?
850 Log.e(TAG, "Error starting restore operation");
851 return;
852 }
853
854 String packageName = mTransport.nextRestorePackage();
855 if (packageName == null) {
856 // STOPSHIP TODO: Handle the failure somehow?
857 Log.e(TAG, "Error getting first restore package");
858 return;
859 } else if (packageName.equals("")) {
860 Log.i(TAG, "No restore data available");
861 return;
862 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
863 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
864 + "\", found only \"" + packageName + "\"");
865 return;
866 }
867
868 // Pull the Package Manager metadata from the restore set first
869 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
870 mPackageManager, agentPackages);
871 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
872
Christopher Tate7d562ec2009-06-25 18:03:43 -0700873 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700874 for (;;) {
875 packageName = mTransport.nextRestorePackage();
876 if (packageName == null) {
877 // STOPSHIP TODO: Handle the failure somehow?
878 Log.e(TAG, "Error getting next restore package");
879 return;
880 } else if (packageName.equals("")) {
881 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700882 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700883
Christopher Tate7d562ec2009-06-25 18:03:43 -0700884 if (mObserver != null) {
885 ++count;
886 try {
887 mObserver.onUpdate(count);
888 } catch (RemoteException e) {
889 Log.d(TAG, "Restore observer died in onUpdate");
890 mObserver = null;
891 }
892 }
893
Dan Egnorefe52642009-06-24 00:16:33 -0700894 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
895 if (metaInfo == null) {
896 Log.e(TAG, "Missing metadata for " + packageName);
897 continue;
898 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700899
Dan Egnorefe52642009-06-24 00:16:33 -0700900 int flags = PackageManager.GET_SIGNATURES;
901 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
902 if (metaInfo.versionCode > packageInfo.versionCode) {
903 Log.w(TAG, "Package " + packageName
904 + " restore version [" + metaInfo.versionCode
905 + "] is too new for installed version ["
906 + packageInfo.versionCode + "]");
907 continue;
908 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700909
Dan Egnorefe52642009-06-24 00:16:33 -0700910 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
911 Log.w(TAG, "Signature mismatch restoring " + packageName);
912 continue;
913 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700914
Dan Egnorefe52642009-06-24 00:16:33 -0700915 if (DEBUG) Log.v(TAG, "Package " + packageName
916 + " restore version [" + metaInfo.versionCode
917 + "] is compatible with installed version ["
918 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700919
Dan Egnorefe52642009-06-24 00:16:33 -0700920 // Now perform the actual restore
921 clearApplicationDataSynchronous(packageName);
922 IBackupAgent agent = bindToAgentSynchronous(
923 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700924 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700925 if (agent == null) {
926 Log.w(TAG, "Can't find backup agent for " + packageName);
927 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700928 }
929
Dan Egnorefe52642009-06-24 00:16:33 -0700930 try {
931 processOneRestore(packageInfo, metaInfo.versionCode, agent);
932 } finally {
933 // unbind even on timeout or failure, just in case
934 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
935 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700936 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700937
938 // if we get this far, report success to the observer
939 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700940 } catch (NameNotFoundException e) {
941 // STOPSHIP TODO: Handle the failure somehow?
942 Log.e(TAG, "Invalid paackage restoring data", e);
943 } catch (RemoteException e) {
944 // STOPSHIP TODO: Handle the failure somehow?
945 Log.e(TAG, "Error restoring data", e);
946 } finally {
947 try {
948 mTransport.finishRestore();
949 } catch (RemoteException e) {
950 Log.e(TAG, "Error finishing restore", e);
951 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700952
953 if (mObserver != null) {
954 try {
955 mObserver.restoreFinished(error);
956 } catch (RemoteException e) {
957 Log.d(TAG, "Restore observer died at restoreFinished");
958 }
959 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700960 }
961 }
962
Dan Egnorefe52642009-06-24 00:16:33 -0700963 // Do the guts of a restore of one application, using mTransport.getRestoreData().
964 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700965 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700966 final String packageName = app.packageName;
967
968 // !!! TODO: get the dirs from the transport
969 File backupDataName = new File(mDataDir, packageName + ".restore");
970 backupDataName.delete();
971 try {
972 ParcelFileDescriptor backupData =
973 ParcelFileDescriptor.open(backupDataName,
974 ParcelFileDescriptor.MODE_READ_WRITE |
975 ParcelFileDescriptor.MODE_CREATE);
976
977 // Run the transport's restore pass
978 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -0700979 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700980 if (!mTransport.getRestoreData(backupData)) {
981 // STOPSHIP TODO: Handle this error somehow?
982 Log.e(TAG, "Error getting restore data for " + packageName);
983 return;
984 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700985 } finally {
986 backupData.close();
987 }
988
989 // Okay, we have the data. Now have the agent do the restore.
990 File newStateName = new File(mStateDir, packageName + ".new");
991 ParcelFileDescriptor newState =
992 ParcelFileDescriptor.open(newStateName,
993 ParcelFileDescriptor.MODE_READ_WRITE |
994 ParcelFileDescriptor.MODE_CREATE);
995
996 backupData = ParcelFileDescriptor.open(backupDataName,
997 ParcelFileDescriptor.MODE_READ_ONLY);
998
Christopher Tatec7b31e32009-06-10 15:49:30 -0700999 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001000 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001001 } finally {
1002 newState.close();
1003 backupData.close();
1004 }
1005
1006 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001007 File savedStateName = new File(mStateDir, packageName);
1008 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001009 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001010 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001011 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001012 }
1013 }
1014
1015
Christopher Tate487529a2009-04-29 14:03:25 -07001016 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001017
Christopher Tatea8bf8152009-04-30 11:36:21 -07001018 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001019 // Record that we need a backup pass for the caller. Since multiple callers
1020 // may share a uid, we need to note all candidates within that uid and schedule
1021 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001022
1023 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001024
1025 // If the caller does not hold the BACKUP permission, it can only request a
1026 // backup of its own data.
1027 HashSet<ApplicationInfo> targets;
1028 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1029 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1030 targets = mBackupParticipants.get(Binder.getCallingUid());
1031 } else {
1032 // a caller with full permission can ask to back up any participating app
1033 // !!! TODO: allow backup of ANY app?
1034 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1035 targets = new HashSet<ApplicationInfo>();
1036 int N = mBackupParticipants.size();
1037 for (int i = 0; i < N; i++) {
1038 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1039 if (s != null) {
1040 targets.addAll(s);
1041 }
1042 }
1043 }
Christopher Tate487529a2009-04-29 14:03:25 -07001044 if (targets != null) {
1045 synchronized (mQueueLock) {
1046 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001047 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001048 // validate the caller-supplied package name against the known set of
1049 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001050 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001051 // Add the caller to the set of pending backups. If there is
1052 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001053 BackupRequest req = new BackupRequest(app, false);
1054 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001055
1056 // Journal this request in case of crash
1057 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001058 }
1059 }
1060
Christopher Tate181fafa2009-05-14 11:12:14 -07001061 if (DEBUG) {
1062 int numKeys = mPendingBackups.size();
1063 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1064 for (BackupRequest b : mPendingBackups.values()) {
1065 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1066 }
1067 }
Christopher Tate487529a2009-04-29 14:03:25 -07001068 // Schedule a backup pass in a few minutes. As backup-eligible data
1069 // keeps changing, continue to defer the backup pass until things
1070 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001071 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001072 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001073 } else {
1074 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001075 }
1076 }
Christopher Tate46758122009-05-06 11:22:00 -07001077
Christopher Tatecde87f42009-06-12 12:55:53 -07001078 private void writeToJournalLocked(String str) {
1079 if (mJournalStream != null) {
1080 try {
1081 mJournalStream.writeUTF(str);
1082 } catch (IOException e) {
1083 Log.e(TAG, "Error writing to backup journal");
1084 mJournalStream = null;
1085 mJournal = null;
1086 }
1087 }
1088 }
1089
Christopher Tateace7f092009-06-15 18:07:25 -07001090 // Run a backup pass immediately for any applications that have declared
1091 // that they have pending updates.
1092 public void backupNow() throws RemoteException {
1093 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001094
Christopher Tateace7f092009-06-15 18:07:25 -07001095 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001096 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001097 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001098 }
1099 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001100
Christopher Tateace7f092009-06-15 18:07:25 -07001101 // Report the currently active transport
1102 public int getCurrentTransport() {
1103 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001104 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001105 return mTransportId;
1106 }
1107
Christopher Tate043dadc2009-06-02 16:11:00 -07001108 // Select which transport to use for the next backup operation
1109 public int selectBackupTransport(int transportId) {
1110 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1111
Dan Egnor87a02bc2009-06-17 02:30:10 -07001112 int prevTransport = mTransportId;
1113 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001114 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001115 return prevTransport;
1116 }
1117
1118 // Callback: a requested backup agent has been instantiated. This should only
1119 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001120 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001121 synchronized(mAgentConnectLock) {
1122 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1123 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1124 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1125 mConnectedAgent = agent;
1126 mConnecting = false;
1127 } else {
1128 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1129 + " claiming agent connected");
1130 }
1131 mAgentConnectLock.notifyAll();
1132 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001133 }
1134
1135 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1136 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001137 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001138 public void agentDisconnected(String packageName) {
1139 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001140 synchronized(mAgentConnectLock) {
1141 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1142 mConnectedAgent = null;
1143 mConnecting = false;
1144 } else {
1145 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1146 + " claiming agent disconnected");
1147 }
1148 mAgentConnectLock.notifyAll();
1149 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001150 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001151
Christopher Tate8c850b72009-06-07 19:33:20 -07001152 // Hand off a restore session
1153 public IRestoreSession beginRestoreSession(int transportID) {
1154 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001155
1156 synchronized(this) {
1157 if (mActiveRestoreSession != null) {
1158 Log.d(TAG, "Restore session requested but one already active");
1159 return null;
1160 }
1161 mActiveRestoreSession = new RestoreSession(transportID);
1162 }
1163 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001164 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001165
Christopher Tate9b3905c2009-06-08 15:24:01 -07001166 // ----- Restore session -----
1167
1168 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001169 private static final String TAG = "RestoreSession";
1170
Christopher Tate9b3905c2009-06-08 15:24:01 -07001171 private IBackupTransport mRestoreTransport = null;
1172 RestoreSet[] mRestoreSets = null;
1173
1174 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001175 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001176 }
1177
1178 // --- Binder interface ---
1179 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001180 mContext.enforceCallingPermission("android.permission.BACKUP",
1181 "getAvailableRestoreSets");
1182
Christopher Tatef68eb502009-06-16 11:02:01 -07001183 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001184 synchronized(this) {
1185 if (mRestoreSets == null) {
1186 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1187 }
1188 return mRestoreSets;
1189 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001190 } catch (RuntimeException e) {
1191 Log.d(TAG, "getAvailableRestoreSets exception");
1192 e.printStackTrace();
1193 throw e;
1194 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001195 }
1196
Dan Egnor156411d2009-06-26 13:20:02 -07001197 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001198 throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001199 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1200
1201 if (mRestoreSets != null) {
1202 for (int i = 0; i < mRestoreSets.length; i++) {
1203 if (token == mRestoreSets[i].token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001204 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001205 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001206 mBackupHandler.sendMessage(msg);
1207 return 0;
1208 }
1209 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001210 } else {
1211 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001212 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001213 return -1;
1214 }
1215
1216 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001217 mContext.enforceCallingPermission("android.permission.BACKUP",
1218 "endRestoreSession");
1219
Dan Egnorefe52642009-06-24 00:16:33 -07001220 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001221 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001222 synchronized(BackupManagerService.this) {
1223 if (BackupManagerService.this.mActiveRestoreSession == this) {
1224 BackupManagerService.this.mActiveRestoreSession = null;
1225 } else {
1226 Log.e(TAG, "ending non-current restore session");
1227 }
1228 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001229 }
1230 }
1231
Christopher Tate043dadc2009-06-02 16:11:00 -07001232
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001233 @Override
1234 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1235 synchronized (mQueueLock) {
1236 int N = mBackupParticipants.size();
1237 pw.println("Participants:");
1238 for (int i=0; i<N; i++) {
1239 int uid = mBackupParticipants.keyAt(i);
1240 pw.print(" uid: ");
1241 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001242 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1243 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001244 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001245 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001246 }
1247 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001248 pw.println("Pending: " + mPendingBackups.size());
1249 for (BackupRequest req : mPendingBackups.values()) {
1250 pw.print(" ");
1251 pw.println(req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001252 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001253 }
1254 }
Christopher Tate487529a2009-04-29 14:03:25 -07001255}