blob: a6639de4aa78ac73244a495625aca9b8f5d5d3b6 [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 Tate8c850b72009-06-07 19:33:20 -070050import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070051import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070052import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070053
Christopher Tate9bbc21a2009-06-10 20:23:25 -070054import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070055import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070056
Christopher Tate6785dd82009-06-18 15:58:25 -070057import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070058import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070059
Christopher Tatecde87f42009-06-12 12:55:53 -070060import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070061import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070062import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070063import java.io.FileNotFoundException;
Christopher Tatec7b31e32009-06-10 15:49:30 -070064import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070065import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070066import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070067import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040068import java.util.ArrayList;
69import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070070import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070071import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070072import java.util.List;
73
74class BackupManagerService extends IBackupManager.Stub {
75 private static final String TAG = "BackupManagerService";
76 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070077
Christopher Tate6785dd82009-06-18 15:58:25 -070078 // Default time to wait after data changes before we back up the data
Christopher Tate111bd4a2009-06-24 17:29:38 -070079 private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070080
81 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070082 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070083 private static final int MSG_RUN_RESTORE = 3;
Christopher Tatec7b31e32009-06-10 15:49:30 -070084
85 // Timeout interval for deciding that a bind or clear-data has taken too long
86 static final long TIMEOUT_INTERVAL = 10 * 1000;
87
Christopher Tate487529a2009-04-29 14:03:25 -070088 private Context mContext;
89 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070090 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070091 private final BackupHandler mBackupHandler = new BackupHandler();
92 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070093 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
94 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070095 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070096 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070097 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070098 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -070099
Christopher Tate181fafa2009-05-14 11:12:14 -0700100 BackupRequest(ApplicationInfo app, boolean isFull) {
101 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700102 fullBackup = isFull;
103 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700104
105 public String toString() {
106 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
107 }
Christopher Tate46758122009-05-06 11:22:00 -0700108 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400109 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700110 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
111 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate6785dd82009-06-18 15:58:25 -0700112 // Do we need to back up the package manager metadata on the next pass?
113 private boolean mDoPackageManager;
114 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700115
116 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700117 private final Object mQueueLock = new Object();
118
Christopher Tate043dadc2009-06-02 16:11:00 -0700119 // The thread performing the sequence of queued backups binds to each app's agent
120 // in succession. Bind notifications are asynchronously delivered through the
121 // Activity Manager; use this lock object to signal when a requested binding has
122 // completed.
123 private final Object mAgentConnectLock = new Object();
124 private IBackupAgent mConnectedAgent;
125 private volatile boolean mConnecting;
126
Christopher Tatec7b31e32009-06-10 15:49:30 -0700127 // A similar synchronicity mechanism around clearing apps' data for restore
128 private final Object mClearDataLock = new Object();
129 private volatile boolean mClearingData;
130
Christopher Tateaa088442009-06-16 18:25:46 -0700131 // Current active transport & restore session
Christopher Tate043dadc2009-06-02 16:11:00 -0700132 private int mTransportId;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700133 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700134 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700135
Christopher Tate22b87872009-05-04 16:41:53 -0700136 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700137 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700138 private File mJournalDir;
139 private File mJournal;
140 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700141
Christopher Tate487529a2009-04-29 14:03:25 -0700142 public BackupManagerService(Context context) {
143 mContext = context;
144 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700145 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700146
Christopher Tate22b87872009-05-04 16:41:53 -0700147 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700148 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700149 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700150 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700151
Christopher Tatecde87f42009-06-12 12:55:53 -0700152 // Set up the backup-request journaling
153 mJournalDir = new File(mStateDir, "pending");
154 mJournalDir.mkdirs();
155 makeJournalLocked(); // okay because no other threads are running yet
156
Christopher Tateabce4e82009-06-18 18:35:32 -0700157 // Build our mapping of uid to backup client services. This implicitly
158 // schedules a backup pass on the Package Manager metadata the first
159 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700160 synchronized (mBackupParticipants) {
161 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700162 }
163
Dan Egnor87a02bc2009-06-17 02:30:10 -0700164 // Set up our transport options and initialize the default transport
165 // TODO: Have transports register themselves somehow?
166 // TODO: Don't create transports that we don't need to?
Dan Egnor6f211282009-06-25 09:28:29 -0700167 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700168 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
169 mGoogleTransport = null;
170
171 // Attach to the Google backup transport.
172 Intent intent = new Intent().setComponent(new ComponentName(
173 "com.google.android.backup",
174 "com.google.android.backup.BackupTransportService"));
175 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700176
Christopher Tatecde87f42009-06-12 12:55:53 -0700177 // Now that we know about valid backup participants, parse any
178 // leftover journal files and schedule a new backup pass
179 parseLeftoverJournals();
180
Christopher Tate3799bc22009-05-06 16:13:56 -0700181 // Register for broadcasts about package install, etc., so we can
182 // update the provider list.
183 IntentFilter filter = new IntentFilter();
184 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
185 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
186 filter.addDataScheme("package");
187 mContext.registerReceiver(mBroadcastReceiver, filter);
188 }
189
Christopher Tatecde87f42009-06-12 12:55:53 -0700190 private void makeJournalLocked() {
191 try {
192 mJournal = File.createTempFile("journal", null, mJournalDir);
193 mJournalStream = new RandomAccessFile(mJournal, "rwd");
194 } catch (IOException e) {
195 Log.e(TAG, "Unable to write backup journals");
196 mJournal = null;
197 mJournalStream = null;
198 }
199 }
200
201 private void parseLeftoverJournals() {
202 if (mJournal != null) {
203 File[] allJournals = mJournalDir.listFiles();
204 for (File f : allJournals) {
205 if (f.compareTo(mJournal) != 0) {
206 // This isn't the current journal, so it must be a leftover. Read
207 // out the package names mentioned there and schedule them for
208 // backup.
209 try {
210 Log.i(TAG, "Found stale backup journal, scheduling:");
211 RandomAccessFile in = new RandomAccessFile(f, "r");
212 while (true) {
213 String packageName = in.readUTF();
214 Log.i(TAG, " + " + packageName);
215 dataChanged(packageName);
216 }
217 } catch (EOFException e) {
218 // no more data; we're done
219 } catch (Exception e) {
220 // can't read it or other error; just skip it
221 } finally {
222 // close/delete the file
223 f.delete();
224 }
225 }
226 }
227 }
228 }
229
Christopher Tate3799bc22009-05-06 16:13:56 -0700230 // ----- Track installation/removal of packages -----
231 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
232 public void onReceive(Context context, Intent intent) {
233 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
234
235 Uri uri = intent.getData();
236 if (uri == null) {
237 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700238 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700239 String pkgName = uri.getSchemeSpecificPart();
240 if (pkgName == null) {
241 return;
242 }
243
244 String action = intent.getAction();
245 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
246 synchronized (mBackupParticipants) {
247 Bundle extras = intent.getExtras();
248 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
249 // The package was just upgraded
250 updatePackageParticipantsLocked(pkgName);
251 } else {
252 // The package was just added
253 addPackageParticipantsLocked(pkgName);
254 }
255 }
256 }
257 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
258 Bundle extras = intent.getExtras();
259 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
260 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
261 } else {
262 synchronized (mBackupParticipants) {
263 removePackageParticipantsLocked(pkgName);
264 }
265 }
266 }
267 }
268 };
269
Dan Egnor87a02bc2009-06-17 02:30:10 -0700270 // ----- Track connection to GoogleBackupTransport service -----
271 ServiceConnection mGoogleConnection = new ServiceConnection() {
272 public void onServiceConnected(ComponentName name, IBinder service) {
273 if (DEBUG) Log.v(TAG, "Connected to Google transport");
274 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
275 }
276
277 public void onServiceDisconnected(ComponentName name) {
278 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
279 mGoogleTransport = null;
280 }
281 };
282
Joe Onorato8ad02812009-05-13 01:41:44 -0400283 // ----- Run the actual backup process asynchronously -----
284
Christopher Tate181fafa2009-05-14 11:12:14 -0700285 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400286 public void handleMessage(Message msg) {
287
288 switch (msg.what) {
289 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700290 {
291 IBackupTransport transport = getTransport(mTransportId);
292 if (transport == null) {
293 Log.v(TAG, "Backup requested but no transport available");
294 break;
295 }
296
Joe Onorato8ad02812009-05-13 01:41:44 -0400297 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700298 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700299 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400300 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700301 if (mPendingBackups.size() == 0) {
302 Log.v(TAG, "Backup requested but nothing pending");
303 break;
304 }
305
Christopher Tate6aa41f42009-06-19 14:14:22 -0700306 for (BackupRequest b: mPendingBackups.values()) {
307 queue.add(b);
Joe Onorato8ad02812009-05-13 01:41:44 -0400308 }
Christopher Tate6aa41f42009-06-19 14:14:22 -0700309 Log.v(TAG, "clearing pending backups");
310 mPendingBackups.clear();
Christopher Tateace7f092009-06-15 18:07:25 -0700311
312 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700313 if (mJournalStream != null) {
314 try {
315 mJournalStream.close();
316 } catch (IOException e) {
317 // don't need to do anything
318 }
319 makeJournalLocked();
320 }
321
322 // At this point, we have started a new journal file, and the old
323 // file identity is being passed to the backup processing thread.
324 // When it completes successfully, that old journal file will be
325 // deleted. If we crash prior to that, the old journal is parsed
326 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400327 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700328
Christopher Tate6aa41f42009-06-19 14:14:22 -0700329 (new PerformBackupThread(transport, queue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700330 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700331 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700332
333 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400334 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700335
336 case MSG_RUN_RESTORE:
337 {
338 int token = msg.arg1;
339 IBackupTransport transport = (IBackupTransport)msg.obj;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700340 (new PerformRestoreThread(transport, token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700341 break;
342 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400343 }
344 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400345 }
346
Christopher Tate181fafa2009-05-14 11:12:14 -0700347 // Add the backup agents in the given package to our set of known backup participants.
348 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700349 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700350 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700351 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700352 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700353 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700354 }
355
Christopher Tate181fafa2009-05-14 11:12:14 -0700356 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700357 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700358 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700359 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
360 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700361 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
362 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700363 }
364 }
365
Dan Egnorefe52642009-06-24 00:16:33 -0700366 for (PackageInfo pkg : targetPkgs) {
367 if (packageName == null || pkg.packageName.equals(packageName)) {
368 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700369 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700370 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700371 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700372 mBackupParticipants.put(uid, set);
373 }
Dan Egnorefe52642009-06-24 00:16:33 -0700374 set.add(pkg.applicationInfo);
Christopher Tate6785dd82009-06-18 15:58:25 -0700375 backUpPackageManagerData();
Christopher Tate3799bc22009-05-06 16:13:56 -0700376 }
Christopher Tate487529a2009-04-29 14:03:25 -0700377 }
378 }
379
Christopher Tate6785dd82009-06-18 15:58:25 -0700380 // Remove the given package's entry from our known active set. If
381 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700382 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700383 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700384 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700385 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700386 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700387 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700388 int flags = PackageManager.GET_SIGNATURES;
389 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700390 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700391 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700392 }
393 } else {
394 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700395 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700396 }
397 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700398 }
399
Joe Onorato8ad02812009-05-13 01:41:44 -0400400 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700401 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700402 if (DEBUG) {
403 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
404 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700405 for (PackageInfo p : agents) {
406 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700407 }
408 }
Dan Egnorefe52642009-06-24 00:16:33 -0700409 for (PackageInfo pkg : agents) {
410 if (packageName == null || pkg.packageName.equals(packageName)) {
411 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700412 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700413 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700414 // Find the existing entry with the same package name, and remove it.
415 // We can't just remove(app) because the instances are different.
416 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700417 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700418 set.remove(entry);
Christopher Tate6785dd82009-06-18 15:58:25 -0700419 backUpPackageManagerData();
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700420 break;
421 }
422 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700423 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700424 mBackupParticipants.delete(uid);
425 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700426 }
427 }
428 }
429 }
430
Christopher Tate181fafa2009-05-14 11:12:14 -0700431 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700432 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700433 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700434 int flags = PackageManager.GET_SIGNATURES;
435 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
436 int N = packages.size();
437 for (int a = N-1; a >= 0; a--) {
438 ApplicationInfo app = packages.get(a).applicationInfo;
439 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
440 || app.backupAgentName == null) {
441 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700442 }
443 }
Dan Egnorefe52642009-06-24 00:16:33 -0700444 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700445 }
Christopher Tateaa088442009-06-16 18:25:46 -0700446
Christopher Tate3799bc22009-05-06 16:13:56 -0700447 // Reset the given package's known backup participants. Unlike add/remove, the update
448 // action cannot be passed a null package name.
449 void updatePackageParticipantsLocked(String packageName) {
450 if (packageName == null) {
451 Log.e(TAG, "updatePackageParticipants called with null package name");
452 return;
453 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700454 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700455
456 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700457 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700458 removePackageParticipantsLockedInner(packageName, allApps);
459 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700460 }
461
Christopher Tate6785dd82009-06-18 15:58:25 -0700462 private void backUpPackageManagerData() {
463 // No need to schedule a backup just for the metadata; just piggyback on
464 // the next actual data backup.
465 synchronized(this) {
466 mDoPackageManager = true;
467 }
468 }
469
470 // The queue lock should be held when scheduling a backup pass
471 private void scheduleBackupPassLocked(long timeFromNowMillis) {
472 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
473 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
474 }
475
Dan Egnor87a02bc2009-06-17 02:30:10 -0700476 // Return the given transport
477 private IBackupTransport getTransport(int transportID) {
Christopher Tate8c850b72009-06-07 19:33:20 -0700478 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700479 case BackupManager.TRANSPORT_LOCAL:
Christopher Tate6785dd82009-06-18 15:58:25 -0700480 Log.v(TAG, "Supplying local transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700481 return mLocalTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700482
483 case BackupManager.TRANSPORT_GOOGLE:
Christopher Tate6785dd82009-06-18 15:58:25 -0700484 Log.v(TAG, "Supplying Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700485 return mGoogleTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700486
487 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700488 Log.e(TAG, "Asked for unknown transport " + transportID);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700489 return null;
Christopher Tate8c850b72009-06-07 19:33:20 -0700490 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700491 }
492
Christopher Tatedf01dea2009-06-09 20:45:02 -0700493 // fire off a backup agent, blocking until it attaches or times out
494 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
495 IBackupAgent agent = null;
496 synchronized(mAgentConnectLock) {
497 mConnecting = true;
498 mConnectedAgent = null;
499 try {
500 if (mActivityManager.bindBackupAgent(app, mode)) {
501 Log.d(TAG, "awaiting agent for " + app);
502
503 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700504 // only wait 10 seconds for the clear data to happen
505 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
506 while (mConnecting && mConnectedAgent == null
507 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700508 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700509 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700510 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700511 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700512 return null;
513 }
514 }
515
516 // if we timed out with no connect, abort and move on
517 if (mConnecting == true) {
518 Log.w(TAG, "Timeout waiting for agent " + app);
519 return null;
520 }
521 agent = mConnectedAgent;
522 }
523 } catch (RemoteException e) {
524 // can't happen
525 }
526 }
527 return agent;
528 }
529
Christopher Tatec7b31e32009-06-10 15:49:30 -0700530 // clear an application's data, blocking until the operation completes or times out
531 void clearApplicationDataSynchronous(String packageName) {
532 ClearDataObserver observer = new ClearDataObserver();
533
534 synchronized(mClearDataLock) {
535 mClearingData = true;
536 mPackageManager.clearApplicationUserData(packageName, observer);
537
538 // only wait 10 seconds for the clear data to happen
539 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
540 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
541 try {
542 mClearDataLock.wait(5000);
543 } catch (InterruptedException e) {
544 // won't happen, but still.
545 mClearingData = false;
546 }
547 }
548 }
549 }
550
551 class ClearDataObserver extends IPackageDataObserver.Stub {
552 public void onRemoveCompleted(String packageName, boolean succeeded)
553 throws android.os.RemoteException {
554 synchronized(mClearDataLock) {
555 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700556 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700557 }
558 }
559 }
560
Christopher Tate043dadc2009-06-02 16:11:00 -0700561 // ----- Back up a set of applications via a worker thread -----
562
563 class PerformBackupThread extends Thread {
564 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700565 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700566 ArrayList<BackupRequest> mQueue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700567 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700568
Christopher Tateaa088442009-06-16 18:25:46 -0700569 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700570 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700571 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700572 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700573 mJournal = journal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700574 }
575
576 @Override
577 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700578 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
579
Dan Egnorefe52642009-06-24 00:16:33 -0700580 // First, back up the package manager metadata if necessary
Christopher Tate6785dd82009-06-18 15:58:25 -0700581 boolean doPackageManager;
582 synchronized (BackupManagerService.this) {
583 doPackageManager = mDoPackageManager;
584 mDoPackageManager = false;
585 }
586 if (doPackageManager) {
587 // The package manager doesn't have a proper <application> etc, but since
588 // it's running here in the system process we can just set up its agent
589 // directly and use a synthetic BackupRequest.
590 if (DEBUG) Log.i(TAG, "Running PM backup pass as well");
591
592 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -0700593 mPackageManager, allAgentPackages());
Christopher Tate6785dd82009-06-18 15:58:25 -0700594 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
595 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
596 processOneBackup(pmRequest,
597 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
598 mTransport);
599 }
600
601 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700602 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700603
604 // Finally, tear down the transport
605 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700606 if (!mTransport.finishBackup()) {
607 // STOPSHIP TODO: handle errors
608 Log.e(TAG, "Backup failure in finishBackup()");
609 }
610 } catch (RemoteException e) {
611 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700612 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700613
614 if (!mJournal.delete()) {
615 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
616 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700617 }
618
619 private void doQueuedBackups(IBackupTransport transport) {
620 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700621 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700622
623 IBackupAgent agent = null;
624 int mode = (request.fullBackup)
625 ? IApplicationThread.BACKUP_MODE_FULL
626 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
627 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700628 agent = bindToAgentSynchronous(request.appInfo, mode);
629 if (agent != null) {
630 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700631 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700632
633 // unbind even on timeout, just in case
634 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700635 } catch (SecurityException ex) {
636 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700637 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700638 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700639 Log.v(TAG, "bind/backup threw");
640 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700641 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700642
Christopher Tate043dadc2009-06-02 16:11:00 -0700643 }
644 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700645
646 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
647 final String packageName = request.appInfo.packageName;
648 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
649
650 try {
651 // Look up the package info & signatures. This is first so that if it
652 // throws an exception, there's no file setup yet that would need to
653 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700654 PackageInfo packInfo;
655 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
656 // The metadata 'package' is synthetic
657 packInfo = new PackageInfo();
658 packInfo.packageName = packageName;
659 } else {
660 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700661 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700662 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700663
664 // !!! TODO: get the state file dir from the transport
665 File savedStateName = new File(mStateDir, packageName);
666 File backupDataName = new File(mDataDir, packageName + ".data");
667 File newStateName = new File(mStateDir, packageName + ".new");
668
669 // In a full backup, we pass a null ParcelFileDescriptor as
670 // the saved-state "file"
671 ParcelFileDescriptor savedState = (request.fullBackup) ? null
672 : ParcelFileDescriptor.open(savedStateName,
673 ParcelFileDescriptor.MODE_READ_ONLY |
674 ParcelFileDescriptor.MODE_CREATE);
675
676 backupDataName.delete();
677 ParcelFileDescriptor backupData =
678 ParcelFileDescriptor.open(backupDataName,
679 ParcelFileDescriptor.MODE_READ_WRITE |
680 ParcelFileDescriptor.MODE_CREATE);
681
682 newStateName.delete();
683 ParcelFileDescriptor newState =
684 ParcelFileDescriptor.open(newStateName,
685 ParcelFileDescriptor.MODE_READ_WRITE |
686 ParcelFileDescriptor.MODE_CREATE);
687
688 // Run the target's backup pass
689 boolean success = false;
690 try {
691 agent.doBackup(savedState, backupData, newState);
692 success = true;
693 } finally {
694 if (savedState != null) {
695 savedState.close();
696 }
697 backupData.close();
698 newState.close();
699 }
700
701 // Now propagate the newly-backed-up data to the transport
702 if (success) {
703 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
704 backupData =
705 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700706 if (!transport.performBackup(packInfo, backupData)) {
707 // STOPSHIP TODO: handle errors
708 Log.e(TAG, "Backup failure in performBackup()");
709 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700710
711 // !!! TODO: After successful transport, delete the now-stale data
712 // and juggle the files so that next time the new state is passed
713 //backupDataName.delete();
714 newStateName.renameTo(savedStateName);
715 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700716 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700717 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700718 }
719 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700720 }
721
Christopher Tatedf01dea2009-06-09 20:45:02 -0700722
723 // ----- Restore handling -----
724
Christopher Tateabce4e82009-06-18 18:35:32 -0700725 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700726 // Allow unsigned apps, but not signed on one device and unsigned on the other
727 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700728 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
729 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700730 if ((storedSigs == null || storedSigs.length == 0)
731 && (deviceSigs == null || deviceSigs.length == 0)) {
732 return true;
733 }
734 if (storedSigs == null || deviceSigs == null) {
735 return false;
736 }
737
Christopher Tateabce4e82009-06-18 18:35:32 -0700738 // !!! TODO: this demands that every stored signature match one
739 // that is present on device, and does not demand the converse.
740 // Is this this right policy?
741 int nStored = storedSigs.length;
742 int nDevice = deviceSigs.length;
743
744 for (int i=0; i < nStored; i++) {
745 boolean match = false;
746 for (int j=0; j < nDevice; j++) {
747 if (storedSigs[i].equals(deviceSigs[j])) {
748 match = true;
749 break;
750 }
751 }
752 if (!match) {
753 return false;
754 }
755 }
756 return true;
757 }
758
Christopher Tatedf01dea2009-06-09 20:45:02 -0700759 class PerformRestoreThread extends Thread {
760 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700761 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700762 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700763
Christopher Tate5cbbf562009-06-22 16:44:51 -0700764 class RestoreRequest {
765 public PackageInfo app;
766 public int storedAppVersion;
767
768 RestoreRequest(PackageInfo _app, int _version) {
769 app = _app;
770 storedAppVersion = _version;
771 }
772 }
773
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700774 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700775 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700776 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700777 }
778
779 @Override
780 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700781 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700782 /**
783 * Restore sequence:
784 *
Dan Egnorefe52642009-06-24 00:16:33 -0700785 * 1. get the restore set description for our identity
786 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700787 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700788 * 3. for each app in the restore queue:
789 * 3.a. clear the app data
790 * 3.b. get the restore data for the app from the transport
791 * 3.c. launch the backup agent for the app
792 * 3.d. agent.doRestore() with the data from the server
793 * 3.e. unbind the agent [and kill the app?]
794 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700795 */
796
Dan Egnorefe52642009-06-24 00:16:33 -0700797 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700798 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700799 RestoreSet[] images = mTransport.getAvailableRestoreSets();
800 if (images == null) {
801 // STOPSHIP TODO: Handle the failure somehow?
802 Log.e(TAG, "Error getting restore sets");
803 return;
804 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700805
Dan Egnorefe52642009-06-24 00:16:33 -0700806 if (images.length == 0) {
807 Log.i(TAG, "No restore sets available");
808 return;
809 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700810
Dan Egnorefe52642009-06-24 00:16:33 -0700811 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700812
Dan Egnorefe52642009-06-24 00:16:33 -0700813 // Get the list of all packages which have backup enabled.
814 // (Include the Package Manager metadata pseudo-package first.)
815 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
816 PackageInfo omPackage = new PackageInfo();
817 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
818 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700819
Dan Egnorefe52642009-06-24 00:16:33 -0700820 List<PackageInfo> agentPackages = allAgentPackages();
821 restorePackages.addAll(agentPackages);
822
823 // STOPSHIP TODO: pick out the set for this token (instead of images[0])
824 long token = images[0].token;
825 if (!mTransport.startRestore(token, restorePackages.toArray(new PackageInfo[0]))) {
826 // STOPSHIP TODO: Handle the failure somehow?
827 Log.e(TAG, "Error starting restore operation");
828 return;
829 }
830
831 String packageName = mTransport.nextRestorePackage();
832 if (packageName == null) {
833 // STOPSHIP TODO: Handle the failure somehow?
834 Log.e(TAG, "Error getting first restore package");
835 return;
836 } else if (packageName.equals("")) {
837 Log.i(TAG, "No restore data available");
838 return;
839 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
840 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
841 + "\", found only \"" + packageName + "\"");
842 return;
843 }
844
845 // Pull the Package Manager metadata from the restore set first
846 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
847 mPackageManager, agentPackages);
848 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
849
850 for (;;) {
851 packageName = mTransport.nextRestorePackage();
852 if (packageName == null) {
853 // STOPSHIP TODO: Handle the failure somehow?
854 Log.e(TAG, "Error getting next restore package");
855 return;
856 } else if (packageName.equals("")) {
857 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700858 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700859
Dan Egnorefe52642009-06-24 00:16:33 -0700860 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
861 if (metaInfo == null) {
862 Log.e(TAG, "Missing metadata for " + packageName);
863 continue;
864 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700865
Dan Egnorefe52642009-06-24 00:16:33 -0700866 int flags = PackageManager.GET_SIGNATURES;
867 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
868 if (metaInfo.versionCode > packageInfo.versionCode) {
869 Log.w(TAG, "Package " + packageName
870 + " restore version [" + metaInfo.versionCode
871 + "] is too new for installed version ["
872 + packageInfo.versionCode + "]");
873 continue;
874 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700875
Dan Egnorefe52642009-06-24 00:16:33 -0700876 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
877 Log.w(TAG, "Signature mismatch restoring " + packageName);
878 continue;
879 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700880
Dan Egnorefe52642009-06-24 00:16:33 -0700881 if (DEBUG) Log.v(TAG, "Package " + packageName
882 + " restore version [" + metaInfo.versionCode
883 + "] is compatible with installed version ["
884 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700885
Dan Egnorefe52642009-06-24 00:16:33 -0700886 // Now perform the actual restore
887 clearApplicationDataSynchronous(packageName);
888 IBackupAgent agent = bindToAgentSynchronous(
889 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700890 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700891 if (agent == null) {
892 Log.w(TAG, "Can't find backup agent for " + packageName);
893 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700894 }
895
Dan Egnorefe52642009-06-24 00:16:33 -0700896 try {
897 processOneRestore(packageInfo, metaInfo.versionCode, agent);
898 } finally {
899 // unbind even on timeout or failure, just in case
900 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
901 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700902 }
Dan Egnorefe52642009-06-24 00:16:33 -0700903 } catch (NameNotFoundException e) {
904 // STOPSHIP TODO: Handle the failure somehow?
905 Log.e(TAG, "Invalid paackage restoring data", e);
906 } catch (RemoteException e) {
907 // STOPSHIP TODO: Handle the failure somehow?
908 Log.e(TAG, "Error restoring data", e);
909 } finally {
910 try {
911 mTransport.finishRestore();
912 } catch (RemoteException e) {
913 Log.e(TAG, "Error finishing restore", e);
914 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700915 }
916 }
917
Dan Egnorefe52642009-06-24 00:16:33 -0700918 // Do the guts of a restore of one application, using mTransport.getRestoreData().
919 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700920 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700921 final String packageName = app.packageName;
922
923 // !!! TODO: get the dirs from the transport
924 File backupDataName = new File(mDataDir, packageName + ".restore");
925 backupDataName.delete();
926 try {
927 ParcelFileDescriptor backupData =
928 ParcelFileDescriptor.open(backupDataName,
929 ParcelFileDescriptor.MODE_READ_WRITE |
930 ParcelFileDescriptor.MODE_CREATE);
931
932 // Run the transport's restore pass
933 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -0700934 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700935 if (!mTransport.getRestoreData(backupData)) {
936 // STOPSHIP TODO: Handle this error somehow?
937 Log.e(TAG, "Error getting restore data for " + packageName);
938 return;
939 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700940 } finally {
941 backupData.close();
942 }
943
944 // Okay, we have the data. Now have the agent do the restore.
945 File newStateName = new File(mStateDir, packageName + ".new");
946 ParcelFileDescriptor newState =
947 ParcelFileDescriptor.open(newStateName,
948 ParcelFileDescriptor.MODE_READ_WRITE |
949 ParcelFileDescriptor.MODE_CREATE);
950
951 backupData = ParcelFileDescriptor.open(backupDataName,
952 ParcelFileDescriptor.MODE_READ_ONLY);
953
Christopher Tatec7b31e32009-06-10 15:49:30 -0700954 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700955 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700956 } finally {
957 newState.close();
958 backupData.close();
959 }
960
961 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -0700962 File savedStateName = new File(mStateDir, packageName);
963 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700964 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700965 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700966 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700967 }
968 }
969
970
Christopher Tate487529a2009-04-29 14:03:25 -0700971 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700972
Christopher Tatea8bf8152009-04-30 11:36:21 -0700973 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700974 // Record that we need a backup pass for the caller. Since multiple callers
975 // may share a uid, we need to note all candidates within that uid and schedule
976 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700977
978 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700979
980 // If the caller does not hold the BACKUP permission, it can only request a
981 // backup of its own data.
982 HashSet<ApplicationInfo> targets;
983 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
984 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
985 targets = mBackupParticipants.get(Binder.getCallingUid());
986 } else {
987 // a caller with full permission can ask to back up any participating app
988 // !!! TODO: allow backup of ANY app?
989 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
990 targets = new HashSet<ApplicationInfo>();
991 int N = mBackupParticipants.size();
992 for (int i = 0; i < N; i++) {
993 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
994 if (s != null) {
995 targets.addAll(s);
996 }
997 }
998 }
Christopher Tate487529a2009-04-29 14:03:25 -0700999 if (targets != null) {
1000 synchronized (mQueueLock) {
1001 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001002 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001003 // validate the caller-supplied package name against the known set of
1004 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001005 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001006 // Add the caller to the set of pending backups. If there is
1007 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001008 BackupRequest req = new BackupRequest(app, false);
1009 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001010
1011 // Journal this request in case of crash
1012 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001013 }
1014 }
1015
Christopher Tate181fafa2009-05-14 11:12:14 -07001016 if (DEBUG) {
1017 int numKeys = mPendingBackups.size();
1018 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1019 for (BackupRequest b : mPendingBackups.values()) {
1020 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1021 }
1022 }
Christopher Tate487529a2009-04-29 14:03:25 -07001023 // Schedule a backup pass in a few minutes. As backup-eligible data
1024 // keeps changing, continue to defer the backup pass until things
1025 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001026 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001027 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001028 } else {
1029 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001030 }
1031 }
Christopher Tate46758122009-05-06 11:22:00 -07001032
Christopher Tatecde87f42009-06-12 12:55:53 -07001033 private void writeToJournalLocked(String str) {
1034 if (mJournalStream != null) {
1035 try {
1036 mJournalStream.writeUTF(str);
1037 } catch (IOException e) {
1038 Log.e(TAG, "Error writing to backup journal");
1039 mJournalStream = null;
1040 mJournal = null;
1041 }
1042 }
1043 }
1044
Christopher Tateace7f092009-06-15 18:07:25 -07001045 // Run a backup pass immediately for any applications that have declared
1046 // that they have pending updates.
1047 public void backupNow() throws RemoteException {
1048 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001049
Christopher Tateace7f092009-06-15 18:07:25 -07001050 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001051 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001052 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001053 }
1054 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001055
Christopher Tateace7f092009-06-15 18:07:25 -07001056 // Report the currently active transport
1057 public int getCurrentTransport() {
1058 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001059 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001060 return mTransportId;
1061 }
1062
Christopher Tate043dadc2009-06-02 16:11:00 -07001063 // Select which transport to use for the next backup operation
1064 public int selectBackupTransport(int transportId) {
1065 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1066
Dan Egnor87a02bc2009-06-17 02:30:10 -07001067 int prevTransport = mTransportId;
1068 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001069 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001070 return prevTransport;
1071 }
1072
1073 // Callback: a requested backup agent has been instantiated. This should only
1074 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001075 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001076 synchronized(mAgentConnectLock) {
1077 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1078 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1079 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1080 mConnectedAgent = agent;
1081 mConnecting = false;
1082 } else {
1083 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1084 + " claiming agent connected");
1085 }
1086 mAgentConnectLock.notifyAll();
1087 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001088 }
1089
1090 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1091 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001092 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001093 public void agentDisconnected(String packageName) {
1094 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001095 synchronized(mAgentConnectLock) {
1096 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1097 mConnectedAgent = null;
1098 mConnecting = false;
1099 } else {
1100 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1101 + " claiming agent disconnected");
1102 }
1103 mAgentConnectLock.notifyAll();
1104 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001105 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001106
Christopher Tate8c850b72009-06-07 19:33:20 -07001107 // Hand off a restore session
1108 public IRestoreSession beginRestoreSession(int transportID) {
1109 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001110
1111 synchronized(this) {
1112 if (mActiveRestoreSession != null) {
1113 Log.d(TAG, "Restore session requested but one already active");
1114 return null;
1115 }
1116 mActiveRestoreSession = new RestoreSession(transportID);
1117 }
1118 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001119 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001120
Christopher Tate9b3905c2009-06-08 15:24:01 -07001121 // ----- Restore session -----
1122
1123 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001124 private static final String TAG = "RestoreSession";
1125
Christopher Tate9b3905c2009-06-08 15:24:01 -07001126 private IBackupTransport mRestoreTransport = null;
1127 RestoreSet[] mRestoreSets = null;
1128
1129 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001130 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001131 }
1132
1133 // --- Binder interface ---
1134 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001135 mContext.enforceCallingPermission("android.permission.BACKUP",
1136 "getAvailableRestoreSets");
1137
Christopher Tatef68eb502009-06-16 11:02:01 -07001138 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001139 synchronized(this) {
1140 if (mRestoreSets == null) {
1141 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1142 }
1143 return mRestoreSets;
1144 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001145 } catch (RuntimeException e) {
1146 Log.d(TAG, "getAvailableRestoreSets exception");
1147 e.printStackTrace();
1148 throw e;
1149 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001150 }
1151
1152 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001153 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1154
1155 if (mRestoreSets != null) {
1156 for (int i = 0; i < mRestoreSets.length; i++) {
1157 if (token == mRestoreSets[i].token) {
1158 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1159 mRestoreTransport);
1160 msg.arg1 = token;
1161 mBackupHandler.sendMessage(msg);
1162 return 0;
1163 }
1164 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001165 } else {
1166 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001167 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001168 return -1;
1169 }
1170
1171 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001172 mContext.enforceCallingPermission("android.permission.BACKUP",
1173 "endRestoreSession");
1174
Dan Egnorefe52642009-06-24 00:16:33 -07001175 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001176 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001177 synchronized(BackupManagerService.this) {
1178 if (BackupManagerService.this.mActiveRestoreSession == this) {
1179 BackupManagerService.this.mActiveRestoreSession = null;
1180 } else {
1181 Log.e(TAG, "ending non-current restore session");
1182 }
1183 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001184 }
1185 }
1186
Christopher Tate043dadc2009-06-02 16:11:00 -07001187
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001188 @Override
1189 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1190 synchronized (mQueueLock) {
1191 int N = mBackupParticipants.size();
1192 pw.println("Participants:");
1193 for (int i=0; i<N; i++) {
1194 int uid = mBackupParticipants.keyAt(i);
1195 pw.print(" uid: ");
1196 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001197 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1198 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001199 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001200 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001201 }
1202 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001203 pw.println("Pending: " + mPendingBackups.size());
1204 for (BackupRequest req : mPendingBackups.values()) {
1205 pw.print(" ");
1206 pw.println(req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001207 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001208 }
1209 }
Christopher Tate487529a2009-04-29 14:03:25 -07001210}