blob: c0f0d749eb95faa129ed10793afe709631b225b4 [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) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700532 // Don't wipe packages marked allowClearUserData=false
533 try {
534 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
535 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
536 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
537 + packageName);
538 return;
539 }
540 } catch (NameNotFoundException e) {
541 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
542 return;
543 }
544
Christopher Tatec7b31e32009-06-10 15:49:30 -0700545 ClearDataObserver observer = new ClearDataObserver();
546
547 synchronized(mClearDataLock) {
548 mClearingData = true;
549 mPackageManager.clearApplicationUserData(packageName, observer);
550
551 // only wait 10 seconds for the clear data to happen
552 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
553 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
554 try {
555 mClearDataLock.wait(5000);
556 } catch (InterruptedException e) {
557 // won't happen, but still.
558 mClearingData = false;
559 }
560 }
561 }
562 }
563
564 class ClearDataObserver extends IPackageDataObserver.Stub {
565 public void onRemoveCompleted(String packageName, boolean succeeded)
566 throws android.os.RemoteException {
567 synchronized(mClearDataLock) {
568 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700569 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700570 }
571 }
572 }
573
Christopher Tate043dadc2009-06-02 16:11:00 -0700574 // ----- Back up a set of applications via a worker thread -----
575
576 class PerformBackupThread extends Thread {
577 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700578 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700579 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700580 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700581 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700582
Christopher Tateaa088442009-06-16 18:25:46 -0700583 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700584 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700585 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700586 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700587 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700588
589 try {
590 mStateDir = new File(mBaseStateDir, transport.transportDirName());
591 } catch (RemoteException e) {
592 // can't happen; the transport is local
593 }
594 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700595 }
596
597 @Override
598 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700599 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
600
Christopher Tate5cb400b2009-06-25 16:03:14 -0700601 // The package manager doesn't have a proper <application> etc, but since
602 // it's running here in the system process we can just set up its agent
603 // directly and use a synthetic BackupRequest. We always run this pass
604 // because it's cheap and this way we guarantee that we don't get out of
605 // step even if we're selecting among various transports at run time.
606 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
607 mPackageManager, allAgentPackages());
608 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
609 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
610 processOneBackup(pmRequest,
611 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
612 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700613
614 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700615 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700616
617 // Finally, tear down the transport
618 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700619 if (!mTransport.finishBackup()) {
620 // STOPSHIP TODO: handle errors
621 Log.e(TAG, "Backup failure in finishBackup()");
622 }
623 } catch (RemoteException e) {
624 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700625 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700626
627 if (!mJournal.delete()) {
628 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
629 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700630 }
631
632 private void doQueuedBackups(IBackupTransport transport) {
633 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700634 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700635
636 IBackupAgent agent = null;
637 int mode = (request.fullBackup)
638 ? IApplicationThread.BACKUP_MODE_FULL
639 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
640 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700641 agent = bindToAgentSynchronous(request.appInfo, mode);
642 if (agent != null) {
643 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700644 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700645
646 // unbind even on timeout, just in case
647 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700648 } catch (SecurityException ex) {
649 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700650 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700651 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700652 Log.v(TAG, "bind/backup threw");
653 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700654 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700655
Christopher Tate043dadc2009-06-02 16:11:00 -0700656 }
657 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700658
659 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
660 final String packageName = request.appInfo.packageName;
661 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
662
663 try {
664 // Look up the package info & signatures. This is first so that if it
665 // throws an exception, there's no file setup yet that would need to
666 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700667 PackageInfo packInfo;
668 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
669 // The metadata 'package' is synthetic
670 packInfo = new PackageInfo();
671 packInfo.packageName = packageName;
672 } else {
673 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700674 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700675 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700676
677 // !!! TODO: get the state file dir from the transport
678 File savedStateName = new File(mStateDir, packageName);
679 File backupDataName = new File(mDataDir, packageName + ".data");
680 File newStateName = new File(mStateDir, packageName + ".new");
681
682 // In a full backup, we pass a null ParcelFileDescriptor as
683 // the saved-state "file"
684 ParcelFileDescriptor savedState = (request.fullBackup) ? null
685 : ParcelFileDescriptor.open(savedStateName,
686 ParcelFileDescriptor.MODE_READ_ONLY |
687 ParcelFileDescriptor.MODE_CREATE);
688
689 backupDataName.delete();
690 ParcelFileDescriptor backupData =
691 ParcelFileDescriptor.open(backupDataName,
692 ParcelFileDescriptor.MODE_READ_WRITE |
693 ParcelFileDescriptor.MODE_CREATE);
694
695 newStateName.delete();
696 ParcelFileDescriptor newState =
697 ParcelFileDescriptor.open(newStateName,
698 ParcelFileDescriptor.MODE_READ_WRITE |
699 ParcelFileDescriptor.MODE_CREATE);
700
701 // Run the target's backup pass
702 boolean success = false;
703 try {
704 agent.doBackup(savedState, backupData, newState);
705 success = true;
706 } finally {
707 if (savedState != null) {
708 savedState.close();
709 }
710 backupData.close();
711 newState.close();
712 }
713
714 // Now propagate the newly-backed-up data to the transport
715 if (success) {
716 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
717 backupData =
718 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700719 if (!transport.performBackup(packInfo, backupData)) {
720 // STOPSHIP TODO: handle errors
721 Log.e(TAG, "Backup failure in performBackup()");
722 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700723
724 // !!! TODO: After successful transport, delete the now-stale data
725 // and juggle the files so that next time the new state is passed
726 //backupDataName.delete();
727 newStateName.renameTo(savedStateName);
728 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700729 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700730 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700731 }
732 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700733 }
734
Christopher Tatedf01dea2009-06-09 20:45:02 -0700735
736 // ----- Restore handling -----
737
Christopher Tateabce4e82009-06-18 18:35:32 -0700738 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700739 // Allow unsigned apps, but not signed on one device and unsigned on the other
740 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700741 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
742 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700743 if ((storedSigs == null || storedSigs.length == 0)
744 && (deviceSigs == null || deviceSigs.length == 0)) {
745 return true;
746 }
747 if (storedSigs == null || deviceSigs == null) {
748 return false;
749 }
750
Christopher Tateabce4e82009-06-18 18:35:32 -0700751 // !!! TODO: this demands that every stored signature match one
752 // that is present on device, and does not demand the converse.
753 // Is this this right policy?
754 int nStored = storedSigs.length;
755 int nDevice = deviceSigs.length;
756
757 for (int i=0; i < nStored; i++) {
758 boolean match = false;
759 for (int j=0; j < nDevice; j++) {
760 if (storedSigs[i].equals(deviceSigs[j])) {
761 match = true;
762 break;
763 }
764 }
765 if (!match) {
766 return false;
767 }
768 }
769 return true;
770 }
771
Christopher Tatedf01dea2009-06-09 20:45:02 -0700772 class PerformRestoreThread extends Thread {
773 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700774 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700775 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700776 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700777 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700778
Christopher Tate5cbbf562009-06-22 16:44:51 -0700779 class RestoreRequest {
780 public PackageInfo app;
781 public int storedAppVersion;
782
783 RestoreRequest(PackageInfo _app, int _version) {
784 app = _app;
785 storedAppVersion = _version;
786 }
787 }
788
Christopher Tate7d562ec2009-06-25 18:03:43 -0700789 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700790 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700791 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700792 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700793 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700794
795 try {
796 mStateDir = new File(mBaseStateDir, transport.transportDirName());
797 } catch (RemoteException e) {
798 // can't happen; the transport is local
799 }
800 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700801 }
802
803 @Override
804 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700805 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700806 /**
807 * Restore sequence:
808 *
Dan Egnorefe52642009-06-24 00:16:33 -0700809 * 1. get the restore set description for our identity
810 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700811 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700812 * 3. for each app in the restore queue:
813 * 3.a. clear the app data
814 * 3.b. get the restore data for the app from the transport
815 * 3.c. launch the backup agent for the app
816 * 3.d. agent.doRestore() with the data from the server
817 * 3.e. unbind the agent [and kill the app?]
818 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700819 */
820
Christopher Tate7d562ec2009-06-25 18:03:43 -0700821 int error = -1; // assume error
822
Dan Egnorefe52642009-06-24 00:16:33 -0700823 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700824 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700825 RestoreSet[] images = mTransport.getAvailableRestoreSets();
826 if (images == null) {
827 // STOPSHIP TODO: Handle the failure somehow?
828 Log.e(TAG, "Error getting restore sets");
829 return;
830 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700831
Dan Egnorefe52642009-06-24 00:16:33 -0700832 if (images.length == 0) {
833 Log.i(TAG, "No restore sets available");
834 return;
835 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700836
Dan Egnorefe52642009-06-24 00:16:33 -0700837 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700838
Dan Egnorefe52642009-06-24 00:16:33 -0700839 // Get the list of all packages which have backup enabled.
840 // (Include the Package Manager metadata pseudo-package first.)
841 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
842 PackageInfo omPackage = new PackageInfo();
843 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
844 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700845
Dan Egnorefe52642009-06-24 00:16:33 -0700846 List<PackageInfo> agentPackages = allAgentPackages();
847 restorePackages.addAll(agentPackages);
848
Christopher Tate7d562ec2009-06-25 18:03:43 -0700849 // let the observer know that we're running
850 if (mObserver != null) {
851 try {
852 // !!! TODO: get an actual count from the transport after
853 // its startRestore() runs?
854 mObserver.restoreStarting(restorePackages.size());
855 } catch (RemoteException e) {
856 Log.d(TAG, "Restore observer died at restoreStarting");
857 mObserver = null;
858 }
859 }
860
Dan Egnor156411d2009-06-26 13:20:02 -0700861 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700862 // STOPSHIP TODO: Handle the failure somehow?
863 Log.e(TAG, "Error starting restore operation");
864 return;
865 }
866
867 String packageName = mTransport.nextRestorePackage();
868 if (packageName == null) {
869 // STOPSHIP TODO: Handle the failure somehow?
870 Log.e(TAG, "Error getting first restore package");
871 return;
872 } else if (packageName.equals("")) {
873 Log.i(TAG, "No restore data available");
874 return;
875 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
876 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
877 + "\", found only \"" + packageName + "\"");
878 return;
879 }
880
881 // Pull the Package Manager metadata from the restore set first
882 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
883 mPackageManager, agentPackages);
884 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
885
Christopher Tate7d562ec2009-06-25 18:03:43 -0700886 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700887 for (;;) {
888 packageName = mTransport.nextRestorePackage();
889 if (packageName == null) {
890 // STOPSHIP TODO: Handle the failure somehow?
891 Log.e(TAG, "Error getting next restore package");
892 return;
893 } else if (packageName.equals("")) {
894 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700895 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700896
Christopher Tate7d562ec2009-06-25 18:03:43 -0700897 if (mObserver != null) {
898 ++count;
899 try {
900 mObserver.onUpdate(count);
901 } catch (RemoteException e) {
902 Log.d(TAG, "Restore observer died in onUpdate");
903 mObserver = null;
904 }
905 }
906
Dan Egnorefe52642009-06-24 00:16:33 -0700907 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
908 if (metaInfo == null) {
909 Log.e(TAG, "Missing metadata for " + packageName);
910 continue;
911 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700912
Dan Egnorefe52642009-06-24 00:16:33 -0700913 int flags = PackageManager.GET_SIGNATURES;
914 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
915 if (metaInfo.versionCode > packageInfo.versionCode) {
916 Log.w(TAG, "Package " + packageName
917 + " restore version [" + metaInfo.versionCode
918 + "] is too new for installed version ["
919 + packageInfo.versionCode + "]");
920 continue;
921 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700922
Dan Egnorefe52642009-06-24 00:16:33 -0700923 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
924 Log.w(TAG, "Signature mismatch restoring " + packageName);
925 continue;
926 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700927
Dan Egnorefe52642009-06-24 00:16:33 -0700928 if (DEBUG) Log.v(TAG, "Package " + packageName
929 + " restore version [" + metaInfo.versionCode
930 + "] is compatible with installed version ["
931 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700932
Dan Egnorefe52642009-06-24 00:16:33 -0700933 // Now perform the actual restore
934 clearApplicationDataSynchronous(packageName);
935 IBackupAgent agent = bindToAgentSynchronous(
936 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700937 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700938 if (agent == null) {
939 Log.w(TAG, "Can't find backup agent for " + packageName);
940 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700941 }
942
Dan Egnorefe52642009-06-24 00:16:33 -0700943 try {
944 processOneRestore(packageInfo, metaInfo.versionCode, agent);
945 } finally {
946 // unbind even on timeout or failure, just in case
947 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
948 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700949 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700950
951 // if we get this far, report success to the observer
952 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700953 } catch (NameNotFoundException e) {
954 // STOPSHIP TODO: Handle the failure somehow?
955 Log.e(TAG, "Invalid paackage restoring data", e);
956 } catch (RemoteException e) {
957 // STOPSHIP TODO: Handle the failure somehow?
958 Log.e(TAG, "Error restoring data", e);
959 } finally {
960 try {
961 mTransport.finishRestore();
962 } catch (RemoteException e) {
963 Log.e(TAG, "Error finishing restore", e);
964 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700965
966 if (mObserver != null) {
967 try {
968 mObserver.restoreFinished(error);
969 } catch (RemoteException e) {
970 Log.d(TAG, "Restore observer died at restoreFinished");
971 }
972 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700973 }
974 }
975
Dan Egnorefe52642009-06-24 00:16:33 -0700976 // Do the guts of a restore of one application, using mTransport.getRestoreData().
977 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700978 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700979 final String packageName = app.packageName;
980
981 // !!! TODO: get the dirs from the transport
982 File backupDataName = new File(mDataDir, packageName + ".restore");
983 backupDataName.delete();
984 try {
985 ParcelFileDescriptor backupData =
986 ParcelFileDescriptor.open(backupDataName,
987 ParcelFileDescriptor.MODE_READ_WRITE |
988 ParcelFileDescriptor.MODE_CREATE);
989
990 // Run the transport's restore pass
991 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -0700992 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700993 if (!mTransport.getRestoreData(backupData)) {
994 // STOPSHIP TODO: Handle this error somehow?
995 Log.e(TAG, "Error getting restore data for " + packageName);
996 return;
997 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700998 } finally {
999 backupData.close();
1000 }
1001
1002 // Okay, we have the data. Now have the agent do the restore.
1003 File newStateName = new File(mStateDir, packageName + ".new");
1004 ParcelFileDescriptor newState =
1005 ParcelFileDescriptor.open(newStateName,
1006 ParcelFileDescriptor.MODE_READ_WRITE |
1007 ParcelFileDescriptor.MODE_CREATE);
1008
1009 backupData = ParcelFileDescriptor.open(backupDataName,
1010 ParcelFileDescriptor.MODE_READ_ONLY);
1011
Christopher Tatec7b31e32009-06-10 15:49:30 -07001012 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001013 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001014 } finally {
1015 newState.close();
1016 backupData.close();
1017 }
1018
1019 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001020 File savedStateName = new File(mStateDir, packageName);
1021 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001022 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001023 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001024 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001025 }
1026 }
1027
1028
Christopher Tate487529a2009-04-29 14:03:25 -07001029 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001030
Christopher Tatea8bf8152009-04-30 11:36:21 -07001031 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001032 // Record that we need a backup pass for the caller. Since multiple callers
1033 // may share a uid, we need to note all candidates within that uid and schedule
1034 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001035
1036 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001037
1038 // If the caller does not hold the BACKUP permission, it can only request a
1039 // backup of its own data.
1040 HashSet<ApplicationInfo> targets;
1041 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1042 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1043 targets = mBackupParticipants.get(Binder.getCallingUid());
1044 } else {
1045 // a caller with full permission can ask to back up any participating app
1046 // !!! TODO: allow backup of ANY app?
1047 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1048 targets = new HashSet<ApplicationInfo>();
1049 int N = mBackupParticipants.size();
1050 for (int i = 0; i < N; i++) {
1051 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1052 if (s != null) {
1053 targets.addAll(s);
1054 }
1055 }
1056 }
Christopher Tate487529a2009-04-29 14:03:25 -07001057 if (targets != null) {
1058 synchronized (mQueueLock) {
1059 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001060 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001061 // validate the caller-supplied package name against the known set of
1062 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001063 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001064 // Add the caller to the set of pending backups. If there is
1065 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001066 BackupRequest req = new BackupRequest(app, false);
1067 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001068
1069 // Journal this request in case of crash
1070 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001071 }
1072 }
1073
Christopher Tate181fafa2009-05-14 11:12:14 -07001074 if (DEBUG) {
1075 int numKeys = mPendingBackups.size();
1076 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1077 for (BackupRequest b : mPendingBackups.values()) {
1078 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1079 }
1080 }
Christopher Tate487529a2009-04-29 14:03:25 -07001081 // Schedule a backup pass in a few minutes. As backup-eligible data
1082 // keeps changing, continue to defer the backup pass until things
1083 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001084 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001085 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001086 } else {
1087 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001088 }
1089 }
Christopher Tate46758122009-05-06 11:22:00 -07001090
Christopher Tatecde87f42009-06-12 12:55:53 -07001091 private void writeToJournalLocked(String str) {
1092 if (mJournalStream != null) {
1093 try {
1094 mJournalStream.writeUTF(str);
1095 } catch (IOException e) {
1096 Log.e(TAG, "Error writing to backup journal");
1097 mJournalStream = null;
1098 mJournal = null;
1099 }
1100 }
1101 }
1102
Christopher Tateace7f092009-06-15 18:07:25 -07001103 // Run a backup pass immediately for any applications that have declared
1104 // that they have pending updates.
1105 public void backupNow() throws RemoteException {
1106 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001107
Christopher Tateace7f092009-06-15 18:07:25 -07001108 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001109 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001110 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001111 }
1112 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001113
Christopher Tateace7f092009-06-15 18:07:25 -07001114 // Report the currently active transport
1115 public int getCurrentTransport() {
1116 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001117 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001118 return mTransportId;
1119 }
1120
Christopher Tate043dadc2009-06-02 16:11:00 -07001121 // Select which transport to use for the next backup operation
1122 public int selectBackupTransport(int transportId) {
1123 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1124
Dan Egnor87a02bc2009-06-17 02:30:10 -07001125 int prevTransport = mTransportId;
1126 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001127 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001128 return prevTransport;
1129 }
1130
1131 // Callback: a requested backup agent has been instantiated. This should only
1132 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001133 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001134 synchronized(mAgentConnectLock) {
1135 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1136 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1137 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1138 mConnectedAgent = agent;
1139 mConnecting = false;
1140 } else {
1141 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1142 + " claiming agent connected");
1143 }
1144 mAgentConnectLock.notifyAll();
1145 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001146 }
1147
1148 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1149 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001150 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001151 public void agentDisconnected(String packageName) {
1152 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001153 synchronized(mAgentConnectLock) {
1154 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1155 mConnectedAgent = null;
1156 mConnecting = false;
1157 } else {
1158 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1159 + " claiming agent disconnected");
1160 }
1161 mAgentConnectLock.notifyAll();
1162 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001163 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001164
Christopher Tate8c850b72009-06-07 19:33:20 -07001165 // Hand off a restore session
1166 public IRestoreSession beginRestoreSession(int transportID) {
1167 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001168
1169 synchronized(this) {
1170 if (mActiveRestoreSession != null) {
1171 Log.d(TAG, "Restore session requested but one already active");
1172 return null;
1173 }
1174 mActiveRestoreSession = new RestoreSession(transportID);
1175 }
1176 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001177 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001178
Christopher Tate9b3905c2009-06-08 15:24:01 -07001179 // ----- Restore session -----
1180
1181 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001182 private static final String TAG = "RestoreSession";
1183
Christopher Tate9b3905c2009-06-08 15:24:01 -07001184 private IBackupTransport mRestoreTransport = null;
1185 RestoreSet[] mRestoreSets = null;
1186
1187 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001188 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001189 }
1190
1191 // --- Binder interface ---
1192 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001193 mContext.enforceCallingPermission("android.permission.BACKUP",
1194 "getAvailableRestoreSets");
1195
Christopher Tatef68eb502009-06-16 11:02:01 -07001196 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001197 synchronized(this) {
1198 if (mRestoreSets == null) {
1199 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1200 }
1201 return mRestoreSets;
1202 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001203 } catch (RuntimeException e) {
1204 Log.d(TAG, "getAvailableRestoreSets exception");
1205 e.printStackTrace();
1206 throw e;
1207 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001208 }
1209
Dan Egnor156411d2009-06-26 13:20:02 -07001210 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001211 throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001212 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1213
1214 if (mRestoreSets != null) {
1215 for (int i = 0; i < mRestoreSets.length; i++) {
1216 if (token == mRestoreSets[i].token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001217 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001218 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001219 mBackupHandler.sendMessage(msg);
1220 return 0;
1221 }
1222 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001223 } else {
1224 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001225 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001226 return -1;
1227 }
1228
1229 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001230 mContext.enforceCallingPermission("android.permission.BACKUP",
1231 "endRestoreSession");
1232
Dan Egnorefe52642009-06-24 00:16:33 -07001233 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001234 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001235 synchronized(BackupManagerService.this) {
1236 if (BackupManagerService.this.mActiveRestoreSession == this) {
1237 BackupManagerService.this.mActiveRestoreSession = null;
1238 } else {
1239 Log.e(TAG, "ending non-current restore session");
1240 }
1241 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001242 }
1243 }
1244
Christopher Tate043dadc2009-06-02 16:11:00 -07001245
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001246 @Override
1247 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1248 synchronized (mQueueLock) {
1249 int N = mBackupParticipants.size();
1250 pw.println("Participants:");
1251 for (int i=0; i<N; i++) {
1252 int uid = mBackupParticipants.keyAt(i);
1253 pw.print(" uid: ");
1254 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001255 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1256 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001257 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001258 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001259 }
1260 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001261 pw.println("Pending: " + mPendingBackups.size());
1262 for (BackupRequest req : mPendingBackups.values()) {
1263 pw.print(" ");
1264 pw.println(req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001265 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001266 }
1267 }
Christopher Tate487529a2009-04-29 14:03:25 -07001268}