blob: bc2eaed02af994032aea2cc1c2f783631231c02c [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;
141
142 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs) {
143 transport = _transport;
144 observer = _obs;
145 }
146 }
147
Christopher Tate5cb400b2009-06-25 16:03:14 -0700148 // Where we keep our journal files and other bookkeeping
149 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700150 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700151 private File mJournalDir;
152 private File mJournal;
153 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700154
Christopher Tate487529a2009-04-29 14:03:25 -0700155 public BackupManagerService(Context context) {
156 mContext = context;
157 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700158 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700159
Christopher Tate22b87872009-05-04 16:41:53 -0700160 // Set up our bookkeeping
Christopher Tate5cb400b2009-06-25 16:03:14 -0700161 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700162 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700163
Christopher Tatecde87f42009-06-12 12:55:53 -0700164 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700165 mJournalDir = new File(mBaseStateDir, "pending");
166 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700167 makeJournalLocked(); // okay because no other threads are running yet
168
Christopher Tateabce4e82009-06-18 18:35:32 -0700169 // Build our mapping of uid to backup client services. This implicitly
170 // schedules a backup pass on the Package Manager metadata the first
171 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700172 synchronized (mBackupParticipants) {
173 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700174 }
175
Dan Egnor87a02bc2009-06-17 02:30:10 -0700176 // Set up our transport options and initialize the default transport
177 // TODO: Have transports register themselves somehow?
178 // TODO: Don't create transports that we don't need to?
Dan Egnor6f211282009-06-25 09:28:29 -0700179 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700180 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
181 mGoogleTransport = null;
182
183 // Attach to the Google backup transport.
184 Intent intent = new Intent().setComponent(new ComponentName(
185 "com.google.android.backup",
186 "com.google.android.backup.BackupTransportService"));
187 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700188
Christopher Tatecde87f42009-06-12 12:55:53 -0700189 // Now that we know about valid backup participants, parse any
190 // leftover journal files and schedule a new backup pass
191 parseLeftoverJournals();
192
Christopher Tate3799bc22009-05-06 16:13:56 -0700193 // Register for broadcasts about package install, etc., so we can
194 // update the provider list.
195 IntentFilter filter = new IntentFilter();
196 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
197 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
198 filter.addDataScheme("package");
199 mContext.registerReceiver(mBroadcastReceiver, filter);
200 }
201
Christopher Tatecde87f42009-06-12 12:55:53 -0700202 private void makeJournalLocked() {
203 try {
204 mJournal = File.createTempFile("journal", null, mJournalDir);
205 mJournalStream = new RandomAccessFile(mJournal, "rwd");
206 } catch (IOException e) {
207 Log.e(TAG, "Unable to write backup journals");
208 mJournal = null;
209 mJournalStream = null;
210 }
211 }
212
213 private void parseLeftoverJournals() {
214 if (mJournal != null) {
215 File[] allJournals = mJournalDir.listFiles();
216 for (File f : allJournals) {
217 if (f.compareTo(mJournal) != 0) {
218 // This isn't the current journal, so it must be a leftover. Read
219 // out the package names mentioned there and schedule them for
220 // backup.
221 try {
222 Log.i(TAG, "Found stale backup journal, scheduling:");
223 RandomAccessFile in = new RandomAccessFile(f, "r");
224 while (true) {
225 String packageName = in.readUTF();
226 Log.i(TAG, " + " + packageName);
227 dataChanged(packageName);
228 }
229 } catch (EOFException e) {
230 // no more data; we're done
231 } catch (Exception e) {
232 // can't read it or other error; just skip it
233 } finally {
234 // close/delete the file
235 f.delete();
236 }
237 }
238 }
239 }
240 }
241
Christopher Tate3799bc22009-05-06 16:13:56 -0700242 // ----- Track installation/removal of packages -----
243 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
244 public void onReceive(Context context, Intent intent) {
245 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
246
247 Uri uri = intent.getData();
248 if (uri == null) {
249 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700250 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700251 String pkgName = uri.getSchemeSpecificPart();
252 if (pkgName == null) {
253 return;
254 }
255
256 String action = intent.getAction();
257 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
258 synchronized (mBackupParticipants) {
259 Bundle extras = intent.getExtras();
260 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
261 // The package was just upgraded
262 updatePackageParticipantsLocked(pkgName);
263 } else {
264 // The package was just added
265 addPackageParticipantsLocked(pkgName);
266 }
267 }
268 }
269 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
270 Bundle extras = intent.getExtras();
271 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
272 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
273 } else {
274 synchronized (mBackupParticipants) {
275 removePackageParticipantsLocked(pkgName);
276 }
277 }
278 }
279 }
280 };
281
Dan Egnor87a02bc2009-06-17 02:30:10 -0700282 // ----- Track connection to GoogleBackupTransport service -----
283 ServiceConnection mGoogleConnection = new ServiceConnection() {
284 public void onServiceConnected(ComponentName name, IBinder service) {
285 if (DEBUG) Log.v(TAG, "Connected to Google transport");
286 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
287 }
288
289 public void onServiceDisconnected(ComponentName name) {
290 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
291 mGoogleTransport = null;
292 }
293 };
294
Joe Onorato8ad02812009-05-13 01:41:44 -0400295 // ----- Run the actual backup process asynchronously -----
296
Christopher Tate181fafa2009-05-14 11:12:14 -0700297 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400298 public void handleMessage(Message msg) {
299
300 switch (msg.what) {
301 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700302 {
303 IBackupTransport transport = getTransport(mTransportId);
304 if (transport == null) {
305 Log.v(TAG, "Backup requested but no transport available");
306 break;
307 }
308
Joe Onorato8ad02812009-05-13 01:41:44 -0400309 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700310 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700311 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400312 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700313 if (mPendingBackups.size() == 0) {
314 Log.v(TAG, "Backup requested but nothing pending");
315 break;
316 }
317
Christopher Tate6aa41f42009-06-19 14:14:22 -0700318 for (BackupRequest b: mPendingBackups.values()) {
319 queue.add(b);
Joe Onorato8ad02812009-05-13 01:41:44 -0400320 }
Christopher Tate6aa41f42009-06-19 14:14:22 -0700321 Log.v(TAG, "clearing pending backups");
322 mPendingBackups.clear();
Christopher Tateace7f092009-06-15 18:07:25 -0700323
324 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700325 if (mJournalStream != null) {
326 try {
327 mJournalStream.close();
328 } catch (IOException e) {
329 // don't need to do anything
330 }
331 makeJournalLocked();
332 }
333
334 // At this point, we have started a new journal file, and the old
335 // file identity is being passed to the backup processing thread.
336 // When it completes successfully, that old journal file will be
337 // deleted. If we crash prior to that, the old journal is parsed
338 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400339 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700340
Christopher Tate6aa41f42009-06-19 14:14:22 -0700341 (new PerformBackupThread(transport, queue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700342 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700343 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700344
345 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400346 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700347
348 case MSG_RUN_RESTORE:
349 {
350 int token = msg.arg1;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700351 RestoreParams params = (RestoreParams)msg.obj;
352 (new PerformRestoreThread(params.transport, params.observer, token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700353 break;
354 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400355 }
356 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400357 }
358
Christopher Tate181fafa2009-05-14 11:12:14 -0700359 // Add the backup agents in the given package to our set of known backup participants.
360 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700361 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700362 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700363 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700364 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700365 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700366 }
367
Christopher Tate181fafa2009-05-14 11:12:14 -0700368 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700369 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700370 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700371 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
372 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700373 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
374 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700375 }
376 }
377
Dan Egnorefe52642009-06-24 00:16:33 -0700378 for (PackageInfo pkg : targetPkgs) {
379 if (packageName == null || pkg.packageName.equals(packageName)) {
380 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700381 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700382 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700383 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700384 mBackupParticipants.put(uid, set);
385 }
Dan Egnorefe52642009-06-24 00:16:33 -0700386 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700387 }
Christopher Tate487529a2009-04-29 14:03:25 -0700388 }
389 }
390
Christopher Tate6785dd82009-06-18 15:58:25 -0700391 // Remove the given package's entry from our known active set. If
392 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700393 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700394 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700395 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700396 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700397 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700398 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700399 int flags = PackageManager.GET_SIGNATURES;
400 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700401 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700402 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700403 }
404 } else {
405 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700406 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700407 }
408 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700409 }
410
Joe Onorato8ad02812009-05-13 01:41:44 -0400411 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700412 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700413 if (DEBUG) {
414 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
415 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700416 for (PackageInfo p : agents) {
417 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700418 }
419 }
Dan Egnorefe52642009-06-24 00:16:33 -0700420 for (PackageInfo pkg : agents) {
421 if (packageName == null || pkg.packageName.equals(packageName)) {
422 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700423 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700424 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700425 // Find the existing entry with the same package name, and remove it.
426 // We can't just remove(app) because the instances are different.
427 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700428 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700429 set.remove(entry);
430 break;
431 }
432 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700433 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700434 mBackupParticipants.delete(uid);
435 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700436 }
437 }
438 }
439 }
440
Christopher Tate181fafa2009-05-14 11:12:14 -0700441 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700442 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700443 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700444 int flags = PackageManager.GET_SIGNATURES;
445 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
446 int N = packages.size();
447 for (int a = N-1; a >= 0; a--) {
448 ApplicationInfo app = packages.get(a).applicationInfo;
449 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
450 || app.backupAgentName == null) {
451 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700452 }
453 }
Dan Egnorefe52642009-06-24 00:16:33 -0700454 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700455 }
Christopher Tateaa088442009-06-16 18:25:46 -0700456
Christopher Tate3799bc22009-05-06 16:13:56 -0700457 // Reset the given package's known backup participants. Unlike add/remove, the update
458 // action cannot be passed a null package name.
459 void updatePackageParticipantsLocked(String packageName) {
460 if (packageName == null) {
461 Log.e(TAG, "updatePackageParticipants called with null package name");
462 return;
463 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700464 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700465
466 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700467 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700468 removePackageParticipantsLockedInner(packageName, allApps);
469 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700470 }
471
Christopher Tate6785dd82009-06-18 15:58:25 -0700472 // The queue lock should be held when scheduling a backup pass
473 private void scheduleBackupPassLocked(long timeFromNowMillis) {
474 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
475 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
476 }
477
Dan Egnor87a02bc2009-06-17 02:30:10 -0700478 // Return the given transport
479 private IBackupTransport getTransport(int transportID) {
Christopher Tate8c850b72009-06-07 19:33:20 -0700480 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700481 case BackupManager.TRANSPORT_LOCAL:
Christopher Tate6785dd82009-06-18 15:58:25 -0700482 Log.v(TAG, "Supplying local transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700483 return mLocalTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700484
485 case BackupManager.TRANSPORT_GOOGLE:
Christopher Tate6785dd82009-06-18 15:58:25 -0700486 Log.v(TAG, "Supplying Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700487 return mGoogleTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700488
489 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700490 Log.e(TAG, "Asked for unknown transport " + transportID);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700491 return null;
Christopher Tate8c850b72009-06-07 19:33:20 -0700492 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700493 }
494
Christopher Tatedf01dea2009-06-09 20:45:02 -0700495 // fire off a backup agent, blocking until it attaches or times out
496 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
497 IBackupAgent agent = null;
498 synchronized(mAgentConnectLock) {
499 mConnecting = true;
500 mConnectedAgent = null;
501 try {
502 if (mActivityManager.bindBackupAgent(app, mode)) {
503 Log.d(TAG, "awaiting agent for " + app);
504
505 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700506 // only wait 10 seconds for the clear data to happen
507 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
508 while (mConnecting && mConnectedAgent == null
509 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700510 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700511 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700512 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700513 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700514 return null;
515 }
516 }
517
518 // if we timed out with no connect, abort and move on
519 if (mConnecting == true) {
520 Log.w(TAG, "Timeout waiting for agent " + app);
521 return null;
522 }
523 agent = mConnectedAgent;
524 }
525 } catch (RemoteException e) {
526 // can't happen
527 }
528 }
529 return agent;
530 }
531
Christopher Tatec7b31e32009-06-10 15:49:30 -0700532 // clear an application's data, blocking until the operation completes or times out
533 void clearApplicationDataSynchronous(String packageName) {
534 ClearDataObserver observer = new ClearDataObserver();
535
536 synchronized(mClearDataLock) {
537 mClearingData = true;
538 mPackageManager.clearApplicationUserData(packageName, observer);
539
540 // only wait 10 seconds for the clear data to happen
541 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
542 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
543 try {
544 mClearDataLock.wait(5000);
545 } catch (InterruptedException e) {
546 // won't happen, but still.
547 mClearingData = false;
548 }
549 }
550 }
551 }
552
553 class ClearDataObserver extends IPackageDataObserver.Stub {
554 public void onRemoveCompleted(String packageName, boolean succeeded)
555 throws android.os.RemoteException {
556 synchronized(mClearDataLock) {
557 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700558 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700559 }
560 }
561 }
562
Christopher Tate043dadc2009-06-02 16:11:00 -0700563 // ----- Back up a set of applications via a worker thread -----
564
565 class PerformBackupThread extends Thread {
566 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700567 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700568 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700569 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700570 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700571
Christopher Tateaa088442009-06-16 18:25:46 -0700572 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700573 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700574 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700575 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700576 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700577
578 try {
579 mStateDir = new File(mBaseStateDir, transport.transportDirName());
580 } catch (RemoteException e) {
581 // can't happen; the transport is local
582 }
583 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700584 }
585
586 @Override
587 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700588 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
589
Christopher Tate5cb400b2009-06-25 16:03:14 -0700590 // The package manager doesn't have a proper <application> etc, but since
591 // it's running here in the system process we can just set up its agent
592 // directly and use a synthetic BackupRequest. We always run this pass
593 // because it's cheap and this way we guarantee that we don't get out of
594 // step even if we're selecting among various transports at run time.
595 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
596 mPackageManager, allAgentPackages());
597 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
598 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
599 processOneBackup(pmRequest,
600 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
601 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700602
603 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700604 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700605
606 // Finally, tear down the transport
607 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700608 if (!mTransport.finishBackup()) {
609 // STOPSHIP TODO: handle errors
610 Log.e(TAG, "Backup failure in finishBackup()");
611 }
612 } catch (RemoteException e) {
613 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700614 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700615
616 if (!mJournal.delete()) {
617 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
618 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700619 }
620
621 private void doQueuedBackups(IBackupTransport transport) {
622 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700623 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700624
625 IBackupAgent agent = null;
626 int mode = (request.fullBackup)
627 ? IApplicationThread.BACKUP_MODE_FULL
628 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
629 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700630 agent = bindToAgentSynchronous(request.appInfo, mode);
631 if (agent != null) {
632 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700633 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700634
635 // unbind even on timeout, just in case
636 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700637 } catch (SecurityException ex) {
638 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700639 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700640 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700641 Log.v(TAG, "bind/backup threw");
642 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700643 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700644
Christopher Tate043dadc2009-06-02 16:11:00 -0700645 }
646 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700647
648 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
649 final String packageName = request.appInfo.packageName;
650 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
651
652 try {
653 // Look up the package info & signatures. This is first so that if it
654 // throws an exception, there's no file setup yet that would need to
655 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700656 PackageInfo packInfo;
657 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
658 // The metadata 'package' is synthetic
659 packInfo = new PackageInfo();
660 packInfo.packageName = packageName;
661 } else {
662 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700663 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700664 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700665
666 // !!! TODO: get the state file dir from the transport
667 File savedStateName = new File(mStateDir, packageName);
668 File backupDataName = new File(mDataDir, packageName + ".data");
669 File newStateName = new File(mStateDir, packageName + ".new");
670
671 // In a full backup, we pass a null ParcelFileDescriptor as
672 // the saved-state "file"
673 ParcelFileDescriptor savedState = (request.fullBackup) ? null
674 : ParcelFileDescriptor.open(savedStateName,
675 ParcelFileDescriptor.MODE_READ_ONLY |
676 ParcelFileDescriptor.MODE_CREATE);
677
678 backupDataName.delete();
679 ParcelFileDescriptor backupData =
680 ParcelFileDescriptor.open(backupDataName,
681 ParcelFileDescriptor.MODE_READ_WRITE |
682 ParcelFileDescriptor.MODE_CREATE);
683
684 newStateName.delete();
685 ParcelFileDescriptor newState =
686 ParcelFileDescriptor.open(newStateName,
687 ParcelFileDescriptor.MODE_READ_WRITE |
688 ParcelFileDescriptor.MODE_CREATE);
689
690 // Run the target's backup pass
691 boolean success = false;
692 try {
693 agent.doBackup(savedState, backupData, newState);
694 success = true;
695 } finally {
696 if (savedState != null) {
697 savedState.close();
698 }
699 backupData.close();
700 newState.close();
701 }
702
703 // Now propagate the newly-backed-up data to the transport
704 if (success) {
705 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
706 backupData =
707 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700708 if (!transport.performBackup(packInfo, backupData)) {
709 // STOPSHIP TODO: handle errors
710 Log.e(TAG, "Backup failure in performBackup()");
711 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700712
713 // !!! TODO: After successful transport, delete the now-stale data
714 // and juggle the files so that next time the new state is passed
715 //backupDataName.delete();
716 newStateName.renameTo(savedStateName);
717 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700718 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700719 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700720 }
721 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700722 }
723
Christopher Tatedf01dea2009-06-09 20:45:02 -0700724
725 // ----- Restore handling -----
726
Christopher Tateabce4e82009-06-18 18:35:32 -0700727 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700728 // Allow unsigned apps, but not signed on one device and unsigned on the other
729 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700730 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
731 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700732 if ((storedSigs == null || storedSigs.length == 0)
733 && (deviceSigs == null || deviceSigs.length == 0)) {
734 return true;
735 }
736 if (storedSigs == null || deviceSigs == null) {
737 return false;
738 }
739
Christopher Tateabce4e82009-06-18 18:35:32 -0700740 // !!! TODO: this demands that every stored signature match one
741 // that is present on device, and does not demand the converse.
742 // Is this this right policy?
743 int nStored = storedSigs.length;
744 int nDevice = deviceSigs.length;
745
746 for (int i=0; i < nStored; i++) {
747 boolean match = false;
748 for (int j=0; j < nDevice; j++) {
749 if (storedSigs[i].equals(deviceSigs[j])) {
750 match = true;
751 break;
752 }
753 }
754 if (!match) {
755 return false;
756 }
757 }
758 return true;
759 }
760
Christopher Tatedf01dea2009-06-09 20:45:02 -0700761 class PerformRestoreThread extends Thread {
762 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700763 private IRestoreObserver mObserver;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700764 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700765 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700766 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700767
Christopher Tate5cbbf562009-06-22 16:44:51 -0700768 class RestoreRequest {
769 public PackageInfo app;
770 public int storedAppVersion;
771
772 RestoreRequest(PackageInfo _app, int _version) {
773 app = _app;
774 storedAppVersion = _version;
775 }
776 }
777
Christopher Tate7d562ec2009-06-25 18:03:43 -0700778 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
779 int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700780 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700781 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700782 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700783
784 try {
785 mStateDir = new File(mBaseStateDir, transport.transportDirName());
786 } catch (RemoteException e) {
787 // can't happen; the transport is local
788 }
789 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700790 }
791
792 @Override
793 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700794 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700795 /**
796 * Restore sequence:
797 *
Dan Egnorefe52642009-06-24 00:16:33 -0700798 * 1. get the restore set description for our identity
799 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700800 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700801 * 3. for each app in the restore queue:
802 * 3.a. clear the app data
803 * 3.b. get the restore data for the app from the transport
804 * 3.c. launch the backup agent for the app
805 * 3.d. agent.doRestore() with the data from the server
806 * 3.e. unbind the agent [and kill the app?]
807 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700808 */
809
Christopher Tate7d562ec2009-06-25 18:03:43 -0700810 int error = -1; // assume error
811
Dan Egnorefe52642009-06-24 00:16:33 -0700812 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700813 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700814 RestoreSet[] images = mTransport.getAvailableRestoreSets();
815 if (images == null) {
816 // STOPSHIP TODO: Handle the failure somehow?
817 Log.e(TAG, "Error getting restore sets");
818 return;
819 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700820
Dan Egnorefe52642009-06-24 00:16:33 -0700821 if (images.length == 0) {
822 Log.i(TAG, "No restore sets available");
823 return;
824 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700825
Dan Egnorefe52642009-06-24 00:16:33 -0700826 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700827
Dan Egnorefe52642009-06-24 00:16:33 -0700828 // Get the list of all packages which have backup enabled.
829 // (Include the Package Manager metadata pseudo-package first.)
830 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
831 PackageInfo omPackage = new PackageInfo();
832 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
833 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700834
Dan Egnorefe52642009-06-24 00:16:33 -0700835 List<PackageInfo> agentPackages = allAgentPackages();
836 restorePackages.addAll(agentPackages);
837
Christopher Tate7d562ec2009-06-25 18:03:43 -0700838 // let the observer know that we're running
839 if (mObserver != null) {
840 try {
841 // !!! TODO: get an actual count from the transport after
842 // its startRestore() runs?
843 mObserver.restoreStarting(restorePackages.size());
844 } catch (RemoteException e) {
845 Log.d(TAG, "Restore observer died at restoreStarting");
846 mObserver = null;
847 }
848 }
849
Dan Egnorefe52642009-06-24 00:16:33 -0700850 // STOPSHIP TODO: pick out the set for this token (instead of images[0])
851 long token = images[0].token;
852 if (!mTransport.startRestore(token, restorePackages.toArray(new PackageInfo[0]))) {
853 // STOPSHIP TODO: Handle the failure somehow?
854 Log.e(TAG, "Error starting restore operation");
855 return;
856 }
857
858 String packageName = mTransport.nextRestorePackage();
859 if (packageName == null) {
860 // STOPSHIP TODO: Handle the failure somehow?
861 Log.e(TAG, "Error getting first restore package");
862 return;
863 } else if (packageName.equals("")) {
864 Log.i(TAG, "No restore data available");
865 return;
866 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
867 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
868 + "\", found only \"" + packageName + "\"");
869 return;
870 }
871
872 // Pull the Package Manager metadata from the restore set first
873 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
874 mPackageManager, agentPackages);
875 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
876
Christopher Tate7d562ec2009-06-25 18:03:43 -0700877 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700878 for (;;) {
879 packageName = mTransport.nextRestorePackage();
880 if (packageName == null) {
881 // STOPSHIP TODO: Handle the failure somehow?
882 Log.e(TAG, "Error getting next restore package");
883 return;
884 } else if (packageName.equals("")) {
885 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700886 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700887
Christopher Tate7d562ec2009-06-25 18:03:43 -0700888 if (mObserver != null) {
889 ++count;
890 try {
891 mObserver.onUpdate(count);
892 } catch (RemoteException e) {
893 Log.d(TAG, "Restore observer died in onUpdate");
894 mObserver = null;
895 }
896 }
897
Dan Egnorefe52642009-06-24 00:16:33 -0700898 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
899 if (metaInfo == null) {
900 Log.e(TAG, "Missing metadata for " + packageName);
901 continue;
902 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700903
Dan Egnorefe52642009-06-24 00:16:33 -0700904 int flags = PackageManager.GET_SIGNATURES;
905 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
906 if (metaInfo.versionCode > packageInfo.versionCode) {
907 Log.w(TAG, "Package " + packageName
908 + " restore version [" + metaInfo.versionCode
909 + "] is too new for installed version ["
910 + packageInfo.versionCode + "]");
911 continue;
912 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700913
Dan Egnorefe52642009-06-24 00:16:33 -0700914 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
915 Log.w(TAG, "Signature mismatch restoring " + packageName);
916 continue;
917 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700918
Dan Egnorefe52642009-06-24 00:16:33 -0700919 if (DEBUG) Log.v(TAG, "Package " + packageName
920 + " restore version [" + metaInfo.versionCode
921 + "] is compatible with installed version ["
922 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700923
Dan Egnorefe52642009-06-24 00:16:33 -0700924 // Now perform the actual restore
925 clearApplicationDataSynchronous(packageName);
926 IBackupAgent agent = bindToAgentSynchronous(
927 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700928 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700929 if (agent == null) {
930 Log.w(TAG, "Can't find backup agent for " + packageName);
931 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700932 }
933
Dan Egnorefe52642009-06-24 00:16:33 -0700934 try {
935 processOneRestore(packageInfo, metaInfo.versionCode, agent);
936 } finally {
937 // unbind even on timeout or failure, just in case
938 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
939 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700940 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700941
942 // if we get this far, report success to the observer
943 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700944 } catch (NameNotFoundException e) {
945 // STOPSHIP TODO: Handle the failure somehow?
946 Log.e(TAG, "Invalid paackage restoring data", e);
947 } catch (RemoteException e) {
948 // STOPSHIP TODO: Handle the failure somehow?
949 Log.e(TAG, "Error restoring data", e);
950 } finally {
951 try {
952 mTransport.finishRestore();
953 } catch (RemoteException e) {
954 Log.e(TAG, "Error finishing restore", e);
955 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700956
957 if (mObserver != null) {
958 try {
959 mObserver.restoreFinished(error);
960 } catch (RemoteException e) {
961 Log.d(TAG, "Restore observer died at restoreFinished");
962 }
963 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700964 }
965 }
966
Dan Egnorefe52642009-06-24 00:16:33 -0700967 // Do the guts of a restore of one application, using mTransport.getRestoreData().
968 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700969 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700970 final String packageName = app.packageName;
971
972 // !!! TODO: get the dirs from the transport
973 File backupDataName = new File(mDataDir, packageName + ".restore");
974 backupDataName.delete();
975 try {
976 ParcelFileDescriptor backupData =
977 ParcelFileDescriptor.open(backupDataName,
978 ParcelFileDescriptor.MODE_READ_WRITE |
979 ParcelFileDescriptor.MODE_CREATE);
980
981 // Run the transport's restore pass
982 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -0700983 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700984 if (!mTransport.getRestoreData(backupData)) {
985 // STOPSHIP TODO: Handle this error somehow?
986 Log.e(TAG, "Error getting restore data for " + packageName);
987 return;
988 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700989 } finally {
990 backupData.close();
991 }
992
993 // Okay, we have the data. Now have the agent do the restore.
994 File newStateName = new File(mStateDir, packageName + ".new");
995 ParcelFileDescriptor newState =
996 ParcelFileDescriptor.open(newStateName,
997 ParcelFileDescriptor.MODE_READ_WRITE |
998 ParcelFileDescriptor.MODE_CREATE);
999
1000 backupData = ParcelFileDescriptor.open(backupDataName,
1001 ParcelFileDescriptor.MODE_READ_ONLY);
1002
Christopher Tatec7b31e32009-06-10 15:49:30 -07001003 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001004 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001005 } finally {
1006 newState.close();
1007 backupData.close();
1008 }
1009
1010 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001011 File savedStateName = new File(mStateDir, packageName);
1012 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001013 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001014 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001015 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001016 }
1017 }
1018
1019
Christopher Tate487529a2009-04-29 14:03:25 -07001020 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001021
Christopher Tatea8bf8152009-04-30 11:36:21 -07001022 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001023 // Record that we need a backup pass for the caller. Since multiple callers
1024 // may share a uid, we need to note all candidates within that uid and schedule
1025 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001026
1027 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001028
1029 // If the caller does not hold the BACKUP permission, it can only request a
1030 // backup of its own data.
1031 HashSet<ApplicationInfo> targets;
1032 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1033 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1034 targets = mBackupParticipants.get(Binder.getCallingUid());
1035 } else {
1036 // a caller with full permission can ask to back up any participating app
1037 // !!! TODO: allow backup of ANY app?
1038 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1039 targets = new HashSet<ApplicationInfo>();
1040 int N = mBackupParticipants.size();
1041 for (int i = 0; i < N; i++) {
1042 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1043 if (s != null) {
1044 targets.addAll(s);
1045 }
1046 }
1047 }
Christopher Tate487529a2009-04-29 14:03:25 -07001048 if (targets != null) {
1049 synchronized (mQueueLock) {
1050 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001051 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001052 // validate the caller-supplied package name against the known set of
1053 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001054 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001055 // Add the caller to the set of pending backups. If there is
1056 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001057 BackupRequest req = new BackupRequest(app, false);
1058 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001059
1060 // Journal this request in case of crash
1061 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001062 }
1063 }
1064
Christopher Tate181fafa2009-05-14 11:12:14 -07001065 if (DEBUG) {
1066 int numKeys = mPendingBackups.size();
1067 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1068 for (BackupRequest b : mPendingBackups.values()) {
1069 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1070 }
1071 }
Christopher Tate487529a2009-04-29 14:03:25 -07001072 // Schedule a backup pass in a few minutes. As backup-eligible data
1073 // keeps changing, continue to defer the backup pass until things
1074 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001075 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001076 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001077 } else {
1078 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001079 }
1080 }
Christopher Tate46758122009-05-06 11:22:00 -07001081
Christopher Tatecde87f42009-06-12 12:55:53 -07001082 private void writeToJournalLocked(String str) {
1083 if (mJournalStream != null) {
1084 try {
1085 mJournalStream.writeUTF(str);
1086 } catch (IOException e) {
1087 Log.e(TAG, "Error writing to backup journal");
1088 mJournalStream = null;
1089 mJournal = null;
1090 }
1091 }
1092 }
1093
Christopher Tateace7f092009-06-15 18:07:25 -07001094 // Run a backup pass immediately for any applications that have declared
1095 // that they have pending updates.
1096 public void backupNow() throws RemoteException {
1097 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001098
Christopher Tateace7f092009-06-15 18:07:25 -07001099 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001100 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001101 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001102 }
1103 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001104
Christopher Tateace7f092009-06-15 18:07:25 -07001105 // Report the currently active transport
1106 public int getCurrentTransport() {
1107 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001108 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001109 return mTransportId;
1110 }
1111
Christopher Tate043dadc2009-06-02 16:11:00 -07001112 // Select which transport to use for the next backup operation
1113 public int selectBackupTransport(int transportId) {
1114 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1115
Dan Egnor87a02bc2009-06-17 02:30:10 -07001116 int prevTransport = mTransportId;
1117 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001118 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001119 return prevTransport;
1120 }
1121
1122 // Callback: a requested backup agent has been instantiated. This should only
1123 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001124 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001125 synchronized(mAgentConnectLock) {
1126 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1127 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1128 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1129 mConnectedAgent = agent;
1130 mConnecting = false;
1131 } else {
1132 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1133 + " claiming agent connected");
1134 }
1135 mAgentConnectLock.notifyAll();
1136 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001137 }
1138
1139 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1140 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001141 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001142 public void agentDisconnected(String packageName) {
1143 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001144 synchronized(mAgentConnectLock) {
1145 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1146 mConnectedAgent = null;
1147 mConnecting = false;
1148 } else {
1149 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1150 + " claiming agent disconnected");
1151 }
1152 mAgentConnectLock.notifyAll();
1153 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001154 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001155
Christopher Tate8c850b72009-06-07 19:33:20 -07001156 // Hand off a restore session
1157 public IRestoreSession beginRestoreSession(int transportID) {
1158 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001159
1160 synchronized(this) {
1161 if (mActiveRestoreSession != null) {
1162 Log.d(TAG, "Restore session requested but one already active");
1163 return null;
1164 }
1165 mActiveRestoreSession = new RestoreSession(transportID);
1166 }
1167 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001168 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001169
Christopher Tate9b3905c2009-06-08 15:24:01 -07001170 // ----- Restore session -----
1171
1172 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001173 private static final String TAG = "RestoreSession";
1174
Christopher Tate9b3905c2009-06-08 15:24:01 -07001175 private IBackupTransport mRestoreTransport = null;
1176 RestoreSet[] mRestoreSets = null;
1177
1178 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001179 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001180 }
1181
1182 // --- Binder interface ---
1183 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001184 mContext.enforceCallingPermission("android.permission.BACKUP",
1185 "getAvailableRestoreSets");
1186
Christopher Tatef68eb502009-06-16 11:02:01 -07001187 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001188 synchronized(this) {
1189 if (mRestoreSets == null) {
1190 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1191 }
1192 return mRestoreSets;
1193 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001194 } catch (RuntimeException e) {
1195 Log.d(TAG, "getAvailableRestoreSets exception");
1196 e.printStackTrace();
1197 throw e;
1198 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001199 }
1200
Christopher Tate7d562ec2009-06-25 18:03:43 -07001201 public int performRestore(int token, IRestoreObserver observer)
1202 throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001203 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1204
1205 if (mRestoreSets != null) {
1206 for (int i = 0; i < mRestoreSets.length; i++) {
1207 if (token == mRestoreSets[i].token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001208 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
1209 msg.obj = new RestoreParams(mRestoreTransport, observer);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001210 msg.arg1 = token;
1211 mBackupHandler.sendMessage(msg);
1212 return 0;
1213 }
1214 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001215 } else {
1216 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001217 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001218 return -1;
1219 }
1220
1221 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001222 mContext.enforceCallingPermission("android.permission.BACKUP",
1223 "endRestoreSession");
1224
Dan Egnorefe52642009-06-24 00:16:33 -07001225 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001226 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001227 synchronized(BackupManagerService.this) {
1228 if (BackupManagerService.this.mActiveRestoreSession == this) {
1229 BackupManagerService.this.mActiveRestoreSession = null;
1230 } else {
1231 Log.e(TAG, "ending non-current restore session");
1232 }
1233 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001234 }
1235 }
1236
Christopher Tate043dadc2009-06-02 16:11:00 -07001237
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001238 @Override
1239 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1240 synchronized (mQueueLock) {
1241 int N = mBackupParticipants.size();
1242 pw.println("Participants:");
1243 for (int i=0; i<N; i++) {
1244 int uid = mBackupParticipants.keyAt(i);
1245 pw.print(" uid: ");
1246 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001247 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1248 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001249 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001250 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001251 }
1252 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001253 pw.println("Pending: " + mPendingBackups.size());
1254 for (BackupRequest req : mPendingBackups.values()) {
1255 pw.print(" ");
1256 pw.println(req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001257 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001258 }
1259 }
Christopher Tate487529a2009-04-29 14:03:25 -07001260}