blob: bbebba320ca5275c832f2d229597764e750714f3 [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 Tate3a31a932009-06-22 15:10:30 -070037import android.os.Build;
Christopher Tate3799bc22009-05-06 16:13:56 -070038import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070039import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070040import android.os.Handler;
41import android.os.IBinder;
42import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070043import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070044import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070045import android.os.RemoteException;
46import android.util.Log;
47import android.util.SparseArray;
48
49import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070050import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070051import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070052import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070053import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070054
Christopher Tate9bbc21a2009-06-10 20:23:25 -070055import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070056import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070057
Christopher Tate6785dd82009-06-18 15:58:25 -070058import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070059import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070060
Christopher Tatecde87f42009-06-12 12:55:53 -070061import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070062import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070063import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070064import java.io.FileNotFoundException;
Christopher Tatec7b31e32009-06-10 15:49:30 -070065import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070066import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070067import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070068import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040069import java.util.ArrayList;
70import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070071import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070072import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070073import java.util.List;
74
75class BackupManagerService extends IBackupManager.Stub {
76 private static final String TAG = "BackupManagerService";
77 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070078
Christopher Tate6785dd82009-06-18 15:58:25 -070079 // Default time to wait after data changes before we back up the data
Christopher Tate111bd4a2009-06-24 17:29:38 -070080 private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070081
82 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070083 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070084 private static final int MSG_RUN_RESTORE = 3;
Christopher Tate7d562ec2009-06-25 18:03:43 -070085 private static final String RESTORE_OBSERVER_KEY = "_resOb";
Christopher Tatec7b31e32009-06-10 15:49:30 -070086
87 // Timeout interval for deciding that a bind or clear-data has taken too long
88 static final long TIMEOUT_INTERVAL = 10 * 1000;
89
Christopher Tate487529a2009-04-29 14:03:25 -070090 private Context mContext;
91 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070092 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070093 private final BackupHandler mBackupHandler = new BackupHandler();
94 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070095 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
96 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070097 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070098 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070099 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700100 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700101
Christopher Tate181fafa2009-05-14 11:12:14 -0700102 BackupRequest(ApplicationInfo app, boolean isFull) {
103 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700104 fullBackup = isFull;
105 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700106
107 public String toString() {
108 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
109 }
Christopher Tate46758122009-05-06 11:22:00 -0700110 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400111 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700112 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
113 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700114
115 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate6785dd82009-06-18 15:58:25 -0700116 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700117
118 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700119 private final Object mQueueLock = new Object();
120
Christopher Tate043dadc2009-06-02 16:11:00 -0700121 // The thread performing the sequence of queued backups binds to each app's agent
122 // in succession. Bind notifications are asynchronously delivered through the
123 // Activity Manager; use this lock object to signal when a requested binding has
124 // completed.
125 private final Object mAgentConnectLock = new Object();
126 private IBackupAgent mConnectedAgent;
127 private volatile boolean mConnecting;
128
Christopher Tatec7b31e32009-06-10 15:49:30 -0700129 // A similar synchronicity mechanism around clearing apps' data for restore
130 private final Object mClearDataLock = new Object();
131 private volatile boolean mClearingData;
132
Christopher Tateaa088442009-06-16 18:25:46 -0700133 // Current active transport & restore session
Christopher Tate043dadc2009-06-02 16:11:00 -0700134 private int mTransportId;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700135 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700136 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700137
Christopher Tate7d562ec2009-06-25 18:03:43 -0700138 private class RestoreParams {
139 public IBackupTransport transport;
140 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700141 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700142
Dan Egnor156411d2009-06-26 13:20:02 -0700143 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700144 transport = _transport;
145 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700146 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700147 }
148 }
149
Christopher Tate5cb400b2009-06-25 16:03:14 -0700150 // Where we keep our journal files and other bookkeeping
151 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700152 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700153 private File mJournalDir;
154 private File mJournal;
155 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700156
Christopher Tate487529a2009-04-29 14:03:25 -0700157 public BackupManagerService(Context context) {
158 mContext = context;
159 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700160 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700161
Christopher Tate22b87872009-05-04 16:41:53 -0700162 // Set up our bookkeeping
Christopher Tate5cb400b2009-06-25 16:03:14 -0700163 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700164 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700165
Christopher Tatecde87f42009-06-12 12:55:53 -0700166 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700167 mJournalDir = new File(mBaseStateDir, "pending");
168 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700169 makeJournalLocked(); // okay because no other threads are running yet
170
Christopher Tateabce4e82009-06-18 18:35:32 -0700171 // Build our mapping of uid to backup client services. This implicitly
172 // schedules a backup pass on the Package Manager metadata the first
173 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700174 synchronized (mBackupParticipants) {
175 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700176 }
177
Dan Egnor87a02bc2009-06-17 02:30:10 -0700178 // Set up our transport options and initialize the default transport
179 // TODO: Have transports register themselves somehow?
180 // TODO: Don't create transports that we don't need to?
Dan Egnor6f211282009-06-25 09:28:29 -0700181 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700182 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
183 mGoogleTransport = null;
184
185 // Attach to the Google backup transport.
186 Intent intent = new Intent().setComponent(new ComponentName(
187 "com.google.android.backup",
188 "com.google.android.backup.BackupTransportService"));
189 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700190
Christopher Tatecde87f42009-06-12 12:55:53 -0700191 // Now that we know about valid backup participants, parse any
192 // leftover journal files and schedule a new backup pass
193 parseLeftoverJournals();
194
Christopher Tate3799bc22009-05-06 16:13:56 -0700195 // Register for broadcasts about package install, etc., so we can
196 // update the provider list.
197 IntentFilter filter = new IntentFilter();
198 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
199 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
200 filter.addDataScheme("package");
201 mContext.registerReceiver(mBroadcastReceiver, filter);
202 }
203
Christopher Tatecde87f42009-06-12 12:55:53 -0700204 private void makeJournalLocked() {
205 try {
206 mJournal = File.createTempFile("journal", null, mJournalDir);
207 mJournalStream = new RandomAccessFile(mJournal, "rwd");
208 } catch (IOException e) {
209 Log.e(TAG, "Unable to write backup journals");
210 mJournal = null;
211 mJournalStream = null;
212 }
213 }
214
215 private void parseLeftoverJournals() {
216 if (mJournal != null) {
217 File[] allJournals = mJournalDir.listFiles();
218 for (File f : allJournals) {
219 if (f.compareTo(mJournal) != 0) {
220 // This isn't the current journal, so it must be a leftover. Read
221 // out the package names mentioned there and schedule them for
222 // backup.
223 try {
224 Log.i(TAG, "Found stale backup journal, scheduling:");
225 RandomAccessFile in = new RandomAccessFile(f, "r");
226 while (true) {
227 String packageName = in.readUTF();
228 Log.i(TAG, " + " + packageName);
229 dataChanged(packageName);
230 }
231 } catch (EOFException e) {
232 // no more data; we're done
233 } catch (Exception e) {
234 // can't read it or other error; just skip it
235 } finally {
236 // close/delete the file
237 f.delete();
238 }
239 }
240 }
241 }
242 }
243
Christopher Tate3799bc22009-05-06 16:13:56 -0700244 // ----- Track installation/removal of packages -----
245 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
246 public void onReceive(Context context, Intent intent) {
247 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
248
249 Uri uri = intent.getData();
250 if (uri == null) {
251 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700252 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700253 String pkgName = uri.getSchemeSpecificPart();
254 if (pkgName == null) {
255 return;
256 }
257
258 String action = intent.getAction();
259 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
260 synchronized (mBackupParticipants) {
261 Bundle extras = intent.getExtras();
262 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
263 // The package was just upgraded
264 updatePackageParticipantsLocked(pkgName);
265 } else {
266 // The package was just added
267 addPackageParticipantsLocked(pkgName);
268 }
269 }
270 }
271 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
272 Bundle extras = intent.getExtras();
273 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
274 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
275 } else {
276 synchronized (mBackupParticipants) {
277 removePackageParticipantsLocked(pkgName);
278 }
279 }
280 }
281 }
282 };
283
Dan Egnor87a02bc2009-06-17 02:30:10 -0700284 // ----- Track connection to GoogleBackupTransport service -----
285 ServiceConnection mGoogleConnection = new ServiceConnection() {
286 public void onServiceConnected(ComponentName name, IBinder service) {
287 if (DEBUG) Log.v(TAG, "Connected to Google transport");
288 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
289 }
290
291 public void onServiceDisconnected(ComponentName name) {
292 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
293 mGoogleTransport = null;
294 }
295 };
296
Joe Onorato8ad02812009-05-13 01:41:44 -0400297 // ----- Run the actual backup process asynchronously -----
298
Christopher Tate181fafa2009-05-14 11:12:14 -0700299 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400300 public void handleMessage(Message msg) {
301
302 switch (msg.what) {
303 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700304 {
305 IBackupTransport transport = getTransport(mTransportId);
306 if (transport == null) {
307 Log.v(TAG, "Backup requested but no transport available");
308 break;
309 }
310
Joe Onorato8ad02812009-05-13 01:41:44 -0400311 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700312 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700313 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400314 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700315 if (mPendingBackups.size() == 0) {
316 Log.v(TAG, "Backup requested but nothing pending");
317 break;
318 }
319
Christopher Tate6aa41f42009-06-19 14:14:22 -0700320 for (BackupRequest b: mPendingBackups.values()) {
321 queue.add(b);
Joe Onorato8ad02812009-05-13 01:41:44 -0400322 }
Christopher Tate6aa41f42009-06-19 14:14:22 -0700323 Log.v(TAG, "clearing pending backups");
324 mPendingBackups.clear();
Christopher Tateace7f092009-06-15 18:07:25 -0700325
326 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700327 if (mJournalStream != null) {
328 try {
329 mJournalStream.close();
330 } catch (IOException e) {
331 // don't need to do anything
332 }
333 makeJournalLocked();
334 }
335
336 // At this point, we have started a new journal file, and the old
337 // file identity is being passed to the backup processing thread.
338 // When it completes successfully, that old journal file will be
339 // deleted. If we crash prior to that, the old journal is parsed
340 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400341 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700342
Christopher Tate6aa41f42009-06-19 14:14:22 -0700343 (new PerformBackupThread(transport, queue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700344 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700345 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700346
347 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400348 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700349
350 case MSG_RUN_RESTORE:
351 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700352 RestoreParams params = (RestoreParams)msg.obj;
Dan Egnor156411d2009-06-26 13:20:02 -0700353 (new PerformRestoreThread(params.transport, params.observer, params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700354 break;
355 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400356 }
357 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400358 }
359
Christopher Tate181fafa2009-05-14 11:12:14 -0700360 // Add the backup agents in the given package to our set of known backup participants.
361 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700362 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700363 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700364 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700365 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700366 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700367 }
368
Christopher Tate181fafa2009-05-14 11:12:14 -0700369 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700370 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700371 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700372 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
373 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700374 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
375 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700376 }
377 }
378
Dan Egnorefe52642009-06-24 00:16:33 -0700379 for (PackageInfo pkg : targetPkgs) {
380 if (packageName == null || pkg.packageName.equals(packageName)) {
381 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700382 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700383 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700384 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700385 mBackupParticipants.put(uid, set);
386 }
Dan Egnorefe52642009-06-24 00:16:33 -0700387 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700388 }
Christopher Tate487529a2009-04-29 14:03:25 -0700389 }
390 }
391
Christopher Tate6785dd82009-06-18 15:58:25 -0700392 // Remove the given package's entry from our known active set. If
393 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700394 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700395 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700396 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700397 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700398 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700399 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700400 int flags = PackageManager.GET_SIGNATURES;
401 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700402 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700403 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700404 }
405 } else {
406 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700407 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700408 }
409 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700410 }
411
Joe Onorato8ad02812009-05-13 01:41:44 -0400412 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700413 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700414 if (DEBUG) {
415 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
416 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700417 for (PackageInfo p : agents) {
418 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700419 }
420 }
Dan Egnorefe52642009-06-24 00:16:33 -0700421 for (PackageInfo pkg : agents) {
422 if (packageName == null || pkg.packageName.equals(packageName)) {
423 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700424 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700425 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700426 // Find the existing entry with the same package name, and remove it.
427 // We can't just remove(app) because the instances are different.
428 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700429 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700430 set.remove(entry);
431 break;
432 }
433 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700434 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700435 mBackupParticipants.delete(uid);
436 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700437 }
438 }
439 }
440 }
441
Christopher Tate181fafa2009-05-14 11:12:14 -0700442 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700443 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700444 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700445 int flags = PackageManager.GET_SIGNATURES;
446 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
447 int N = packages.size();
448 for (int a = N-1; a >= 0; a--) {
449 ApplicationInfo app = packages.get(a).applicationInfo;
450 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
451 || app.backupAgentName == null) {
452 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700453 }
454 }
Dan Egnorefe52642009-06-24 00:16:33 -0700455 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700456 }
Christopher Tateaa088442009-06-16 18:25:46 -0700457
Christopher Tate3799bc22009-05-06 16:13:56 -0700458 // Reset the given package's known backup participants. Unlike add/remove, the update
459 // action cannot be passed a null package name.
460 void updatePackageParticipantsLocked(String packageName) {
461 if (packageName == null) {
462 Log.e(TAG, "updatePackageParticipants called with null package name");
463 return;
464 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700465 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700466
467 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700468 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700469 removePackageParticipantsLockedInner(packageName, allApps);
470 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700471 }
472
Christopher Tate6785dd82009-06-18 15:58:25 -0700473 // The queue lock should be held when scheduling a backup pass
474 private void scheduleBackupPassLocked(long timeFromNowMillis) {
475 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
476 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
477 }
478
Dan Egnor87a02bc2009-06-17 02:30:10 -0700479 // Return the given transport
480 private IBackupTransport getTransport(int transportID) {
Christopher Tate8c850b72009-06-07 19:33:20 -0700481 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700482 case BackupManager.TRANSPORT_LOCAL:
Christopher Tate6785dd82009-06-18 15:58:25 -0700483 Log.v(TAG, "Supplying local transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700484 return mLocalTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700485
486 case BackupManager.TRANSPORT_GOOGLE:
Christopher Tate6785dd82009-06-18 15:58:25 -0700487 Log.v(TAG, "Supplying Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700488 return mGoogleTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700489
490 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700491 Log.e(TAG, "Asked for unknown transport " + transportID);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700492 return null;
Christopher Tate8c850b72009-06-07 19:33:20 -0700493 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700494 }
495
Christopher Tatedf01dea2009-06-09 20:45:02 -0700496 // fire off a backup agent, blocking until it attaches or times out
497 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
498 IBackupAgent agent = null;
499 synchronized(mAgentConnectLock) {
500 mConnecting = true;
501 mConnectedAgent = null;
502 try {
503 if (mActivityManager.bindBackupAgent(app, mode)) {
504 Log.d(TAG, "awaiting agent for " + app);
505
506 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700507 // only wait 10 seconds for the clear data to happen
508 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
509 while (mConnecting && mConnectedAgent == null
510 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700511 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700512 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700513 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700514 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700515 return null;
516 }
517 }
518
519 // if we timed out with no connect, abort and move on
520 if (mConnecting == true) {
521 Log.w(TAG, "Timeout waiting for agent " + app);
522 return null;
523 }
524 agent = mConnectedAgent;
525 }
526 } catch (RemoteException e) {
527 // can't happen
528 }
529 }
530 return agent;
531 }
532
Christopher Tatec7b31e32009-06-10 15:49:30 -0700533 // clear an application's data, blocking until the operation completes or times out
534 void clearApplicationDataSynchronous(String packageName) {
535 ClearDataObserver observer = new ClearDataObserver();
536
537 synchronized(mClearDataLock) {
538 mClearingData = true;
539 mPackageManager.clearApplicationUserData(packageName, observer);
540
541 // only wait 10 seconds for the clear data to happen
542 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
543 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
544 try {
545 mClearDataLock.wait(5000);
546 } catch (InterruptedException e) {
547 // won't happen, but still.
548 mClearingData = false;
549 }
550 }
551 }
552 }
553
554 class ClearDataObserver extends IPackageDataObserver.Stub {
555 public void onRemoveCompleted(String packageName, boolean succeeded)
556 throws android.os.RemoteException {
557 synchronized(mClearDataLock) {
558 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700559 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700560 }
561 }
562 }
563
Christopher Tate043dadc2009-06-02 16:11:00 -0700564 // ----- Back up a set of applications via a worker thread -----
565
566 class PerformBackupThread extends Thread {
567 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700568 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700569 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700570 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700571 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700572
Christopher Tateaa088442009-06-16 18:25:46 -0700573 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700574 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700575 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700576 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700577 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700578
579 try {
580 mStateDir = new File(mBaseStateDir, transport.transportDirName());
581 } catch (RemoteException e) {
582 // can't happen; the transport is local
583 }
584 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700585 }
586
587 @Override
588 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700589 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
590
Christopher Tate5cb400b2009-06-25 16:03:14 -0700591 // The package manager doesn't have a proper <application> etc, but since
592 // it's running here in the system process we can just set up its agent
593 // directly and use a synthetic BackupRequest. We always run this pass
594 // because it's cheap and this way we guarantee that we don't get out of
595 // step even if we're selecting among various transports at run time.
596 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
597 mPackageManager, allAgentPackages());
598 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
599 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
600 processOneBackup(pmRequest,
601 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
602 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700603
604 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700605 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700606
607 // Finally, tear down the transport
608 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700609 if (!mTransport.finishBackup()) {
610 // STOPSHIP TODO: handle errors
611 Log.e(TAG, "Backup failure in finishBackup()");
612 }
613 } catch (RemoteException e) {
614 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700615 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700616
617 if (!mJournal.delete()) {
618 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
619 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700620 }
621
622 private void doQueuedBackups(IBackupTransport transport) {
623 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700624 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700625
626 IBackupAgent agent = null;
627 int mode = (request.fullBackup)
628 ? IApplicationThread.BACKUP_MODE_FULL
629 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
630 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700631 agent = bindToAgentSynchronous(request.appInfo, mode);
632 if (agent != null) {
633 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700634 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700635
636 // unbind even on timeout, just in case
637 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700638 } catch (SecurityException ex) {
639 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700640 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700641 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700642 Log.v(TAG, "bind/backup threw");
643 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700644 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700645
Christopher Tate043dadc2009-06-02 16:11:00 -0700646 }
647 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700648
649 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
650 final String packageName = request.appInfo.packageName;
651 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
652
653 try {
654 // Look up the package info & signatures. This is first so that if it
655 // throws an exception, there's no file setup yet that would need to
656 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700657 PackageInfo packInfo;
658 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
659 // The metadata 'package' is synthetic
660 packInfo = new PackageInfo();
661 packInfo.packageName = packageName;
662 } else {
663 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700664 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700665 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700666
667 // !!! TODO: get the state file dir from the transport
668 File savedStateName = new File(mStateDir, packageName);
669 File backupDataName = new File(mDataDir, packageName + ".data");
670 File newStateName = new File(mStateDir, packageName + ".new");
671
672 // In a full backup, we pass a null ParcelFileDescriptor as
673 // the saved-state "file"
674 ParcelFileDescriptor savedState = (request.fullBackup) ? null
675 : ParcelFileDescriptor.open(savedStateName,
676 ParcelFileDescriptor.MODE_READ_ONLY |
677 ParcelFileDescriptor.MODE_CREATE);
678
679 backupDataName.delete();
680 ParcelFileDescriptor backupData =
681 ParcelFileDescriptor.open(backupDataName,
682 ParcelFileDescriptor.MODE_READ_WRITE |
683 ParcelFileDescriptor.MODE_CREATE);
684
685 newStateName.delete();
686 ParcelFileDescriptor newState =
687 ParcelFileDescriptor.open(newStateName,
688 ParcelFileDescriptor.MODE_READ_WRITE |
689 ParcelFileDescriptor.MODE_CREATE);
690
691 // Run the target's backup pass
692 boolean success = false;
693 try {
694 agent.doBackup(savedState, backupData, newState);
695 success = true;
696 } finally {
697 if (savedState != null) {
698 savedState.close();
699 }
700 backupData.close();
701 newState.close();
702 }
703
704 // Now propagate the newly-backed-up data to the transport
705 if (success) {
706 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
707 backupData =
708 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700709 if (!transport.performBackup(packInfo, backupData)) {
710 // STOPSHIP TODO: handle errors
711 Log.e(TAG, "Backup failure in performBackup()");
712 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700713
714 // !!! TODO: After successful transport, delete the now-stale data
715 // and juggle the files so that next time the new state is passed
716 //backupDataName.delete();
717 newStateName.renameTo(savedStateName);
718 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700719 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700720 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700721 }
722 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700723 }
724
Christopher Tatedf01dea2009-06-09 20:45:02 -0700725
726 // ----- Restore handling -----
727
Christopher Tateabce4e82009-06-18 18:35:32 -0700728 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700729 // Allow unsigned apps, but not signed on one device and unsigned on the other
730 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700731 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
732 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700733 if ((storedSigs == null || storedSigs.length == 0)
734 && (deviceSigs == null || deviceSigs.length == 0)) {
735 return true;
736 }
737 if (storedSigs == null || deviceSigs == null) {
738 return false;
739 }
740
Christopher Tateabce4e82009-06-18 18:35:32 -0700741 // !!! TODO: this demands that every stored signature match one
742 // that is present on device, and does not demand the converse.
743 // Is this this right policy?
744 int nStored = storedSigs.length;
745 int nDevice = deviceSigs.length;
746
747 for (int i=0; i < nStored; i++) {
748 boolean match = false;
749 for (int j=0; j < nDevice; j++) {
750 if (storedSigs[i].equals(deviceSigs[j])) {
751 match = true;
752 break;
753 }
754 }
755 if (!match) {
756 return false;
757 }
758 }
759 return true;
760 }
761
Christopher Tatedf01dea2009-06-09 20:45:02 -0700762 class PerformRestoreThread extends Thread {
763 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700764 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700765 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700766 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700767 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700768
Christopher Tate5cbbf562009-06-22 16:44:51 -0700769 class RestoreRequest {
770 public PackageInfo app;
771 public int storedAppVersion;
772
773 RestoreRequest(PackageInfo _app, int _version) {
774 app = _app;
775 storedAppVersion = _version;
776 }
777 }
778
Christopher Tate7d562ec2009-06-25 18:03:43 -0700779 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700780 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700781 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700782 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700783 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700784
785 try {
786 mStateDir = new File(mBaseStateDir, transport.transportDirName());
787 } catch (RemoteException e) {
788 // can't happen; the transport is local
789 }
790 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700791 }
792
793 @Override
794 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700795 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700796 /**
797 * Restore sequence:
798 *
Dan Egnorefe52642009-06-24 00:16:33 -0700799 * 1. get the restore set description for our identity
800 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700801 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700802 * 3. for each app in the restore queue:
803 * 3.a. clear the app data
804 * 3.b. get the restore data for the app from the transport
805 * 3.c. launch the backup agent for the app
806 * 3.d. agent.doRestore() with the data from the server
807 * 3.e. unbind the agent [and kill the app?]
808 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700809 */
810
Christopher Tate7d562ec2009-06-25 18:03:43 -0700811 int error = -1; // assume error
812
Dan Egnorefe52642009-06-24 00:16:33 -0700813 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700814 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700815 RestoreSet[] images = mTransport.getAvailableRestoreSets();
816 if (images == null) {
817 // STOPSHIP TODO: Handle the failure somehow?
818 Log.e(TAG, "Error getting restore sets");
819 return;
820 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700821
Dan Egnorefe52642009-06-24 00:16:33 -0700822 if (images.length == 0) {
823 Log.i(TAG, "No restore sets available");
824 return;
825 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700826
Dan Egnorefe52642009-06-24 00:16:33 -0700827 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700828
Dan Egnorefe52642009-06-24 00:16:33 -0700829 // Get the list of all packages which have backup enabled.
830 // (Include the Package Manager metadata pseudo-package first.)
831 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
832 PackageInfo omPackage = new PackageInfo();
833 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
834 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700835
Dan Egnorefe52642009-06-24 00:16:33 -0700836 List<PackageInfo> agentPackages = allAgentPackages();
837 restorePackages.addAll(agentPackages);
838
Christopher Tate7d562ec2009-06-25 18:03:43 -0700839 // let the observer know that we're running
840 if (mObserver != null) {
841 try {
842 // !!! TODO: get an actual count from the transport after
843 // its startRestore() runs?
844 mObserver.restoreStarting(restorePackages.size());
845 } catch (RemoteException e) {
846 Log.d(TAG, "Restore observer died at restoreStarting");
847 mObserver = null;
848 }
849 }
850
Dan Egnor156411d2009-06-26 13:20:02 -0700851 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700852 // STOPSHIP TODO: Handle the failure somehow?
853 Log.e(TAG, "Error starting restore operation");
854 return;
855 }
856
857 String packageName = mTransport.nextRestorePackage();
858 if (packageName == null) {
859 // STOPSHIP TODO: Handle the failure somehow?
860 Log.e(TAG, "Error getting first restore package");
861 return;
862 } else if (packageName.equals("")) {
863 Log.i(TAG, "No restore data available");
864 return;
865 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
866 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
867 + "\", found only \"" + packageName + "\"");
868 return;
869 }
870
871 // Pull the Package Manager metadata from the restore set first
872 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
873 mPackageManager, agentPackages);
874 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
875
Christopher Tate7d562ec2009-06-25 18:03:43 -0700876 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700877 for (;;) {
878 packageName = mTransport.nextRestorePackage();
879 if (packageName == null) {
880 // STOPSHIP TODO: Handle the failure somehow?
881 Log.e(TAG, "Error getting next restore package");
882 return;
883 } else if (packageName.equals("")) {
884 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700885 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700886
Christopher Tate7d562ec2009-06-25 18:03:43 -0700887 if (mObserver != null) {
888 ++count;
889 try {
890 mObserver.onUpdate(count);
891 } catch (RemoteException e) {
892 Log.d(TAG, "Restore observer died in onUpdate");
893 mObserver = null;
894 }
895 }
896
Dan Egnorefe52642009-06-24 00:16:33 -0700897 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
898 if (metaInfo == null) {
899 Log.e(TAG, "Missing metadata for " + packageName);
900 continue;
901 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700902
Dan Egnorefe52642009-06-24 00:16:33 -0700903 int flags = PackageManager.GET_SIGNATURES;
904 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
905 if (metaInfo.versionCode > packageInfo.versionCode) {
906 Log.w(TAG, "Package " + packageName
907 + " restore version [" + metaInfo.versionCode
908 + "] is too new for installed version ["
909 + packageInfo.versionCode + "]");
910 continue;
911 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700912
Dan Egnorefe52642009-06-24 00:16:33 -0700913 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
914 Log.w(TAG, "Signature mismatch restoring " + packageName);
915 continue;
916 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700917
Dan Egnorefe52642009-06-24 00:16:33 -0700918 if (DEBUG) Log.v(TAG, "Package " + packageName
919 + " restore version [" + metaInfo.versionCode
920 + "] is compatible with installed version ["
921 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700922
Dan Egnorefe52642009-06-24 00:16:33 -0700923 // Now perform the actual restore
924 clearApplicationDataSynchronous(packageName);
925 IBackupAgent agent = bindToAgentSynchronous(
926 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700927 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700928 if (agent == null) {
929 Log.w(TAG, "Can't find backup agent for " + packageName);
930 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700931 }
932
Dan Egnorefe52642009-06-24 00:16:33 -0700933 try {
934 processOneRestore(packageInfo, metaInfo.versionCode, agent);
935 } finally {
936 // unbind even on timeout or failure, just in case
937 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
938 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700939 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700940
941 // if we get this far, report success to the observer
942 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700943 } catch (NameNotFoundException e) {
944 // STOPSHIP TODO: Handle the failure somehow?
945 Log.e(TAG, "Invalid paackage restoring data", e);
946 } catch (RemoteException e) {
947 // STOPSHIP TODO: Handle the failure somehow?
948 Log.e(TAG, "Error restoring data", e);
949 } finally {
950 try {
951 mTransport.finishRestore();
952 } catch (RemoteException e) {
953 Log.e(TAG, "Error finishing restore", e);
954 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700955
956 if (mObserver != null) {
957 try {
958 mObserver.restoreFinished(error);
959 } catch (RemoteException e) {
960 Log.d(TAG, "Restore observer died at restoreFinished");
961 }
962 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700963 }
964 }
965
Dan Egnorefe52642009-06-24 00:16:33 -0700966 // Do the guts of a restore of one application, using mTransport.getRestoreData().
967 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700968 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700969 final String packageName = app.packageName;
970
971 // !!! TODO: get the dirs from the transport
972 File backupDataName = new File(mDataDir, packageName + ".restore");
973 backupDataName.delete();
974 try {
975 ParcelFileDescriptor backupData =
976 ParcelFileDescriptor.open(backupDataName,
977 ParcelFileDescriptor.MODE_READ_WRITE |
978 ParcelFileDescriptor.MODE_CREATE);
979
980 // Run the transport's restore pass
981 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -0700982 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700983 if (!mTransport.getRestoreData(backupData)) {
984 // STOPSHIP TODO: Handle this error somehow?
985 Log.e(TAG, "Error getting restore data for " + packageName);
986 return;
987 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700988 } finally {
989 backupData.close();
990 }
991
992 // Okay, we have the data. Now have the agent do the restore.
993 File newStateName = new File(mStateDir, packageName + ".new");
994 ParcelFileDescriptor newState =
995 ParcelFileDescriptor.open(newStateName,
996 ParcelFileDescriptor.MODE_READ_WRITE |
997 ParcelFileDescriptor.MODE_CREATE);
998
999 backupData = ParcelFileDescriptor.open(backupDataName,
1000 ParcelFileDescriptor.MODE_READ_ONLY);
1001
Christopher Tatec7b31e32009-06-10 15:49:30 -07001002 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001003 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001004 } finally {
1005 newState.close();
1006 backupData.close();
1007 }
1008
1009 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001010 File savedStateName = new File(mStateDir, packageName);
1011 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001012 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001013 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001014 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001015 }
1016 }
1017
1018
Christopher Tate487529a2009-04-29 14:03:25 -07001019 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001020
Christopher Tatea8bf8152009-04-30 11:36:21 -07001021 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001022 // Record that we need a backup pass for the caller. Since multiple callers
1023 // may share a uid, we need to note all candidates within that uid and schedule
1024 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001025
1026 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001027
1028 // If the caller does not hold the BACKUP permission, it can only request a
1029 // backup of its own data.
1030 HashSet<ApplicationInfo> targets;
1031 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1032 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1033 targets = mBackupParticipants.get(Binder.getCallingUid());
1034 } else {
1035 // a caller with full permission can ask to back up any participating app
1036 // !!! TODO: allow backup of ANY app?
1037 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1038 targets = new HashSet<ApplicationInfo>();
1039 int N = mBackupParticipants.size();
1040 for (int i = 0; i < N; i++) {
1041 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1042 if (s != null) {
1043 targets.addAll(s);
1044 }
1045 }
1046 }
Christopher Tate487529a2009-04-29 14:03:25 -07001047 if (targets != null) {
1048 synchronized (mQueueLock) {
1049 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001050 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001051 // validate the caller-supplied package name against the known set of
1052 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001053 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001054 // Add the caller to the set of pending backups. If there is
1055 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001056 BackupRequest req = new BackupRequest(app, false);
1057 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001058
1059 // Journal this request in case of crash
1060 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001061 }
1062 }
1063
Christopher Tate181fafa2009-05-14 11:12:14 -07001064 if (DEBUG) {
1065 int numKeys = mPendingBackups.size();
1066 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1067 for (BackupRequest b : mPendingBackups.values()) {
1068 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1069 }
1070 }
Christopher Tate487529a2009-04-29 14:03:25 -07001071 // Schedule a backup pass in a few minutes. As backup-eligible data
1072 // keeps changing, continue to defer the backup pass until things
1073 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001074 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001075 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001076 } else {
1077 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001078 }
1079 }
Christopher Tate46758122009-05-06 11:22:00 -07001080
Christopher Tatecde87f42009-06-12 12:55:53 -07001081 private void writeToJournalLocked(String str) {
1082 if (mJournalStream != null) {
1083 try {
1084 mJournalStream.writeUTF(str);
1085 } catch (IOException e) {
1086 Log.e(TAG, "Error writing to backup journal");
1087 mJournalStream = null;
1088 mJournal = null;
1089 }
1090 }
1091 }
1092
Christopher Tateace7f092009-06-15 18:07:25 -07001093 // Run a backup pass immediately for any applications that have declared
1094 // that they have pending updates.
1095 public void backupNow() throws RemoteException {
1096 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001097
Christopher Tateace7f092009-06-15 18:07:25 -07001098 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001099 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001100 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001101 }
1102 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001103
Christopher Tateace7f092009-06-15 18:07:25 -07001104 // Report the currently active transport
1105 public int getCurrentTransport() {
1106 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001107 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001108 return mTransportId;
1109 }
1110
Christopher Tate043dadc2009-06-02 16:11:00 -07001111 // Select which transport to use for the next backup operation
1112 public int selectBackupTransport(int transportId) {
1113 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1114
Dan Egnor87a02bc2009-06-17 02:30:10 -07001115 int prevTransport = mTransportId;
1116 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001117 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001118 return prevTransport;
1119 }
1120
1121 // Callback: a requested backup agent has been instantiated. This should only
1122 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001123 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001124 synchronized(mAgentConnectLock) {
1125 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1126 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1127 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1128 mConnectedAgent = agent;
1129 mConnecting = false;
1130 } else {
1131 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1132 + " claiming agent connected");
1133 }
1134 mAgentConnectLock.notifyAll();
1135 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001136 }
1137
1138 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1139 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001140 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001141 public void agentDisconnected(String packageName) {
1142 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001143 synchronized(mAgentConnectLock) {
1144 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1145 mConnectedAgent = null;
1146 mConnecting = false;
1147 } else {
1148 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1149 + " claiming agent disconnected");
1150 }
1151 mAgentConnectLock.notifyAll();
1152 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001153 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001154
Christopher Tate8c850b72009-06-07 19:33:20 -07001155 // Hand off a restore session
1156 public IRestoreSession beginRestoreSession(int transportID) {
1157 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001158
1159 synchronized(this) {
1160 if (mActiveRestoreSession != null) {
1161 Log.d(TAG, "Restore session requested but one already active");
1162 return null;
1163 }
1164 mActiveRestoreSession = new RestoreSession(transportID);
1165 }
1166 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001167 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001168
Christopher Tate9b3905c2009-06-08 15:24:01 -07001169 // ----- Restore session -----
1170
1171 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001172 private static final String TAG = "RestoreSession";
1173
Christopher Tate9b3905c2009-06-08 15:24:01 -07001174 private IBackupTransport mRestoreTransport = null;
1175 RestoreSet[] mRestoreSets = null;
1176
1177 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001178 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001179 }
1180
1181 // --- Binder interface ---
1182 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001183 mContext.enforceCallingPermission("android.permission.BACKUP",
1184 "getAvailableRestoreSets");
1185
Christopher Tatef68eb502009-06-16 11:02:01 -07001186 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001187 synchronized(this) {
1188 if (mRestoreSets == null) {
1189 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1190 }
1191 return mRestoreSets;
1192 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001193 } catch (RuntimeException e) {
1194 Log.d(TAG, "getAvailableRestoreSets exception");
1195 e.printStackTrace();
1196 throw e;
1197 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001198 }
1199
Dan Egnor156411d2009-06-26 13:20:02 -07001200 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001201 throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001202 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1203
1204 if (mRestoreSets != null) {
1205 for (int i = 0; i < mRestoreSets.length; i++) {
1206 if (token == mRestoreSets[i].token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001207 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001208 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001209 mBackupHandler.sendMessage(msg);
1210 return 0;
1211 }
1212 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001213 } else {
1214 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001215 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001216 return -1;
1217 }
1218
1219 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001220 mContext.enforceCallingPermission("android.permission.BACKUP",
1221 "endRestoreSession");
1222
Dan Egnorefe52642009-06-24 00:16:33 -07001223 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001224 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001225 synchronized(BackupManagerService.this) {
1226 if (BackupManagerService.this.mActiveRestoreSession == this) {
1227 BackupManagerService.this.mActiveRestoreSession = null;
1228 } else {
1229 Log.e(TAG, "ending non-current restore session");
1230 }
1231 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001232 }
1233 }
1234
Christopher Tate043dadc2009-06-02 16:11:00 -07001235
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001236 @Override
1237 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1238 synchronized (mQueueLock) {
1239 int N = mBackupParticipants.size();
1240 pw.println("Participants:");
1241 for (int i=0; i<N; i++) {
1242 int uid = mBackupParticipants.keyAt(i);
1243 pw.print(" uid: ");
1244 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001245 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1246 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001247 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001248 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001249 }
1250 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001251 pw.println("Pending: " + mPendingBackups.size());
1252 for (BackupRequest req : mPendingBackups.values()) {
1253 pw.print(" ");
1254 pw.println(req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001255 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001256 }
1257 }
Christopher Tate487529a2009-04-29 14:03:25 -07001258}