blob: fdd4617b58a43e05da4c14b82cd0236905c23167 [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
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070079 private static final long COLLECTION_INTERVAL = 1000;
80 //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 Tatec7b31e32009-06-10 15:49:30 -070085
86 // Timeout interval for deciding that a bind or clear-data has taken too long
87 static final long TIMEOUT_INTERVAL = 10 * 1000;
88
Christopher Tate487529a2009-04-29 14:03:25 -070089 private Context mContext;
90 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070091 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070092 private final BackupHandler mBackupHandler = new BackupHandler();
93 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070094 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
95 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070096 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070097 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070098 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070099 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700100
Christopher Tate181fafa2009-05-14 11:12:14 -0700101 BackupRequest(ApplicationInfo app, boolean isFull) {
102 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700103 fullBackup = isFull;
104 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700105
106 public String toString() {
107 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
108 }
Christopher Tate46758122009-05-06 11:22:00 -0700109 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400110 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700111 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
112 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate6785dd82009-06-18 15:58:25 -0700113 // Do we need to back up the package manager metadata on the next pass?
114 private boolean mDoPackageManager;
115 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700116
117 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700118 private final Object mQueueLock = new Object();
119
Christopher Tate043dadc2009-06-02 16:11:00 -0700120 // The thread performing the sequence of queued backups binds to each app's agent
121 // in succession. Bind notifications are asynchronously delivered through the
122 // Activity Manager; use this lock object to signal when a requested binding has
123 // completed.
124 private final Object mAgentConnectLock = new Object();
125 private IBackupAgent mConnectedAgent;
126 private volatile boolean mConnecting;
127
Christopher Tatec7b31e32009-06-10 15:49:30 -0700128 // A similar synchronicity mechanism around clearing apps' data for restore
129 private final Object mClearDataLock = new Object();
130 private volatile boolean mClearingData;
131
Christopher Tateaa088442009-06-16 18:25:46 -0700132 // Current active transport & restore session
Christopher Tate043dadc2009-06-02 16:11:00 -0700133 private int mTransportId;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700134 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700135 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700136
Christopher Tate22b87872009-05-04 16:41:53 -0700137 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700138 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700139 private File mJournalDir;
140 private File mJournal;
141 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700142
Christopher Tate487529a2009-04-29 14:03:25 -0700143 public BackupManagerService(Context context) {
144 mContext = context;
145 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700146 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700147
Christopher Tate22b87872009-05-04 16:41:53 -0700148 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700149 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700150 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700151 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700152
Christopher Tatecde87f42009-06-12 12:55:53 -0700153 // Set up the backup-request journaling
154 mJournalDir = new File(mStateDir, "pending");
155 mJournalDir.mkdirs();
156 makeJournalLocked(); // okay because no other threads are running yet
157
Christopher Tateabce4e82009-06-18 18:35:32 -0700158 // Build our mapping of uid to backup client services. This implicitly
159 // schedules a backup pass on the Package Manager metadata the first
160 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700161 synchronized (mBackupParticipants) {
162 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700163 }
164
Dan Egnor87a02bc2009-06-17 02:30:10 -0700165 // Set up our transport options and initialize the default transport
166 // TODO: Have transports register themselves somehow?
167 // TODO: Don't create transports that we don't need to?
Joe Onorato06290a42009-06-18 20:10:37 -0700168 mTransportId = BackupManager.TRANSPORT_LOCAL;
169 //mTransportId = BackupManager.TRANSPORT_GOOGLE;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700170 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
171 mGoogleTransport = null;
172
173 // Attach to the Google backup transport.
174 Intent intent = new Intent().setComponent(new ComponentName(
175 "com.google.android.backup",
176 "com.google.android.backup.BackupTransportService"));
177 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700178
Christopher Tatecde87f42009-06-12 12:55:53 -0700179 // Now that we know about valid backup participants, parse any
180 // leftover journal files and schedule a new backup pass
181 parseLeftoverJournals();
182
Christopher Tate3799bc22009-05-06 16:13:56 -0700183 // Register for broadcasts about package install, etc., so we can
184 // update the provider list.
185 IntentFilter filter = new IntentFilter();
186 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
187 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
188 filter.addDataScheme("package");
189 mContext.registerReceiver(mBroadcastReceiver, filter);
190 }
191
Christopher Tatecde87f42009-06-12 12:55:53 -0700192 private void makeJournalLocked() {
193 try {
194 mJournal = File.createTempFile("journal", null, mJournalDir);
195 mJournalStream = new RandomAccessFile(mJournal, "rwd");
196 } catch (IOException e) {
197 Log.e(TAG, "Unable to write backup journals");
198 mJournal = null;
199 mJournalStream = null;
200 }
201 }
202
203 private void parseLeftoverJournals() {
204 if (mJournal != null) {
205 File[] allJournals = mJournalDir.listFiles();
206 for (File f : allJournals) {
207 if (f.compareTo(mJournal) != 0) {
208 // This isn't the current journal, so it must be a leftover. Read
209 // out the package names mentioned there and schedule them for
210 // backup.
211 try {
212 Log.i(TAG, "Found stale backup journal, scheduling:");
213 RandomAccessFile in = new RandomAccessFile(f, "r");
214 while (true) {
215 String packageName = in.readUTF();
216 Log.i(TAG, " + " + packageName);
217 dataChanged(packageName);
218 }
219 } catch (EOFException e) {
220 // no more data; we're done
221 } catch (Exception e) {
222 // can't read it or other error; just skip it
223 } finally {
224 // close/delete the file
225 f.delete();
226 }
227 }
228 }
229 }
230 }
231
Christopher Tate3799bc22009-05-06 16:13:56 -0700232 // ----- Track installation/removal of packages -----
233 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
234 public void onReceive(Context context, Intent intent) {
235 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
236
237 Uri uri = intent.getData();
238 if (uri == null) {
239 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700240 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700241 String pkgName = uri.getSchemeSpecificPart();
242 if (pkgName == null) {
243 return;
244 }
245
246 String action = intent.getAction();
247 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
248 synchronized (mBackupParticipants) {
249 Bundle extras = intent.getExtras();
250 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
251 // The package was just upgraded
252 updatePackageParticipantsLocked(pkgName);
253 } else {
254 // The package was just added
255 addPackageParticipantsLocked(pkgName);
256 }
257 }
258 }
259 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
260 Bundle extras = intent.getExtras();
261 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
262 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
263 } else {
264 synchronized (mBackupParticipants) {
265 removePackageParticipantsLocked(pkgName);
266 }
267 }
268 }
269 }
270 };
271
Dan Egnor87a02bc2009-06-17 02:30:10 -0700272 // ----- Track connection to GoogleBackupTransport service -----
273 ServiceConnection mGoogleConnection = new ServiceConnection() {
274 public void onServiceConnected(ComponentName name, IBinder service) {
275 if (DEBUG) Log.v(TAG, "Connected to Google transport");
276 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
277 }
278
279 public void onServiceDisconnected(ComponentName name) {
280 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
281 mGoogleTransport = null;
282 }
283 };
284
Joe Onorato8ad02812009-05-13 01:41:44 -0400285 // ----- Run the actual backup process asynchronously -----
286
Christopher Tate181fafa2009-05-14 11:12:14 -0700287 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400288 public void handleMessage(Message msg) {
289
290 switch (msg.what) {
291 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700292 {
293 IBackupTransport transport = getTransport(mTransportId);
294 if (transport == null) {
295 Log.v(TAG, "Backup requested but no transport available");
296 break;
297 }
298
Joe Onorato8ad02812009-05-13 01:41:44 -0400299 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700300 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700301 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400302 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700303 if (mPendingBackups.size() == 0) {
304 Log.v(TAG, "Backup requested but nothing pending");
305 break;
306 }
307
Christopher Tate6aa41f42009-06-19 14:14:22 -0700308 for (BackupRequest b: mPendingBackups.values()) {
309 queue.add(b);
Joe Onorato8ad02812009-05-13 01:41:44 -0400310 }
Christopher Tate6aa41f42009-06-19 14:14:22 -0700311 Log.v(TAG, "clearing pending backups");
312 mPendingBackups.clear();
Christopher Tateace7f092009-06-15 18:07:25 -0700313
314 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700315 if (mJournalStream != null) {
316 try {
317 mJournalStream.close();
318 } catch (IOException e) {
319 // don't need to do anything
320 }
321 makeJournalLocked();
322 }
323
324 // At this point, we have started a new journal file, and the old
325 // file identity is being passed to the backup processing thread.
326 // When it completes successfully, that old journal file will be
327 // deleted. If we crash prior to that, the old journal is parsed
328 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400329 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700330
Christopher Tate6aa41f42009-06-19 14:14:22 -0700331 (new PerformBackupThread(transport, queue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700332 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700333 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700334
335 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400336 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700337
338 case MSG_RUN_RESTORE:
339 {
340 int token = msg.arg1;
341 IBackupTransport transport = (IBackupTransport)msg.obj;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700342 (new PerformRestoreThread(transport, token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700343 break;
344 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400345 }
346 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400347 }
348
Christopher Tate181fafa2009-05-14 11:12:14 -0700349 // Add the backup agents in the given package to our set of known backup participants.
350 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700351 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700352 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700353 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700354 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700355 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700356 }
357
Christopher Tate181fafa2009-05-14 11:12:14 -0700358 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700359 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700360 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700361 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
362 for (PackageInfo p : targetPkgs) {
363 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700364 }
365 }
366
Dan Egnorefe52642009-06-24 00:16:33 -0700367 for (PackageInfo pkg : targetPkgs) {
368 if (packageName == null || pkg.packageName.equals(packageName)) {
369 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700370 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700371 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700372 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700373 mBackupParticipants.put(uid, set);
374 }
Dan Egnorefe52642009-06-24 00:16:33 -0700375 set.add(pkg.applicationInfo);
Christopher Tate6785dd82009-06-18 15:58:25 -0700376 backUpPackageManagerData();
Christopher Tate3799bc22009-05-06 16:13:56 -0700377 }
Christopher Tate487529a2009-04-29 14:03:25 -0700378 }
379 }
380
Christopher Tate6785dd82009-06-18 15:58:25 -0700381 // Remove the given package's entry from our known active set. If
382 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700383 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700384 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700385 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700386 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700387 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700388 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700389 int flags = PackageManager.GET_SIGNATURES;
390 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700391 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700392 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700393 }
394 } else {
395 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700396 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700397 }
398 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700399 }
400
Joe Onorato8ad02812009-05-13 01:41:44 -0400401 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700402 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700403 if (DEBUG) {
404 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
405 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700406 for (PackageInfo p : agents) {
407 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700408 }
409 }
Dan Egnorefe52642009-06-24 00:16:33 -0700410 for (PackageInfo pkg : agents) {
411 if (packageName == null || pkg.packageName.equals(packageName)) {
412 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700413 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700414 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700415 // Find the existing entry with the same package name, and remove it.
416 // We can't just remove(app) because the instances are different.
417 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700418 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700419 set.remove(entry);
Christopher Tate6785dd82009-06-18 15:58:25 -0700420 backUpPackageManagerData();
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700421 break;
422 }
423 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700424 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700425 mBackupParticipants.delete(uid);
426 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700427 }
428 }
429 }
430 }
431
Christopher Tate181fafa2009-05-14 11:12:14 -0700432 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700433 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700434 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700435 int flags = PackageManager.GET_SIGNATURES;
436 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
437 int N = packages.size();
438 for (int a = N-1; a >= 0; a--) {
439 ApplicationInfo app = packages.get(a).applicationInfo;
440 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
441 || app.backupAgentName == null) {
442 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700443 }
444 }
Dan Egnorefe52642009-06-24 00:16:33 -0700445 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700446 }
Christopher Tateaa088442009-06-16 18:25:46 -0700447
Christopher Tate3799bc22009-05-06 16:13:56 -0700448 // Reset the given package's known backup participants. Unlike add/remove, the update
449 // action cannot be passed a null package name.
450 void updatePackageParticipantsLocked(String packageName) {
451 if (packageName == null) {
452 Log.e(TAG, "updatePackageParticipants called with null package name");
453 return;
454 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700455 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700456
457 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700458 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700459 removePackageParticipantsLockedInner(packageName, allApps);
460 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700461 }
462
Christopher Tate6785dd82009-06-18 15:58:25 -0700463 private void backUpPackageManagerData() {
464 // No need to schedule a backup just for the metadata; just piggyback on
465 // the next actual data backup.
466 synchronized(this) {
467 mDoPackageManager = true;
468 }
469 }
470
471 // The queue lock should be held when scheduling a backup pass
472 private void scheduleBackupPassLocked(long timeFromNowMillis) {
473 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
474 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
475 }
476
Dan Egnor87a02bc2009-06-17 02:30:10 -0700477 // Return the given transport
478 private IBackupTransport getTransport(int transportID) {
Christopher Tate8c850b72009-06-07 19:33:20 -0700479 switch (transportID) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700480 case BackupManager.TRANSPORT_LOCAL:
Christopher Tate6785dd82009-06-18 15:58:25 -0700481 Log.v(TAG, "Supplying local transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700482 return mLocalTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700483
484 case BackupManager.TRANSPORT_GOOGLE:
Christopher Tate6785dd82009-06-18 15:58:25 -0700485 Log.v(TAG, "Supplying Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700486 return mGoogleTransport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700487
488 default:
Christopher Tatef68eb502009-06-16 11:02:01 -0700489 Log.e(TAG, "Asked for unknown transport " + transportID);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700490 return null;
Christopher Tate8c850b72009-06-07 19:33:20 -0700491 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700492 }
493
Christopher Tatedf01dea2009-06-09 20:45:02 -0700494 // fire off a backup agent, blocking until it attaches or times out
495 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
496 IBackupAgent agent = null;
497 synchronized(mAgentConnectLock) {
498 mConnecting = true;
499 mConnectedAgent = null;
500 try {
501 if (mActivityManager.bindBackupAgent(app, mode)) {
502 Log.d(TAG, "awaiting agent for " + app);
503
504 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700505 // only wait 10 seconds for the clear data to happen
506 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
507 while (mConnecting && mConnectedAgent == null
508 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700509 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700510 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700511 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700512 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700513 return null;
514 }
515 }
516
517 // if we timed out with no connect, abort and move on
518 if (mConnecting == true) {
519 Log.w(TAG, "Timeout waiting for agent " + app);
520 return null;
521 }
522 agent = mConnectedAgent;
523 }
524 } catch (RemoteException e) {
525 // can't happen
526 }
527 }
528 return agent;
529 }
530
Christopher Tatec7b31e32009-06-10 15:49:30 -0700531 // clear an application's data, blocking until the operation completes or times out
532 void clearApplicationDataSynchronous(String packageName) {
533 ClearDataObserver observer = new ClearDataObserver();
534
535 synchronized(mClearDataLock) {
536 mClearingData = true;
537 mPackageManager.clearApplicationUserData(packageName, observer);
538
539 // only wait 10 seconds for the clear data to happen
540 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
541 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
542 try {
543 mClearDataLock.wait(5000);
544 } catch (InterruptedException e) {
545 // won't happen, but still.
546 mClearingData = false;
547 }
548 }
549 }
550 }
551
552 class ClearDataObserver extends IPackageDataObserver.Stub {
553 public void onRemoveCompleted(String packageName, boolean succeeded)
554 throws android.os.RemoteException {
555 synchronized(mClearDataLock) {
556 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700557 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700558 }
559 }
560 }
561
Christopher Tate043dadc2009-06-02 16:11:00 -0700562 // ----- Back up a set of applications via a worker thread -----
563
564 class PerformBackupThread extends Thread {
565 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700566 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700567 ArrayList<BackupRequest> mQueue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700568 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700569
Christopher Tateaa088442009-06-16 18:25:46 -0700570 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700571 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700572 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700573 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700574 mJournal = journal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700575 }
576
577 @Override
578 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700579 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
580
Dan Egnorefe52642009-06-24 00:16:33 -0700581 // First, back up the package manager metadata if necessary
Christopher Tate6785dd82009-06-18 15:58:25 -0700582 boolean doPackageManager;
583 synchronized (BackupManagerService.this) {
584 doPackageManager = mDoPackageManager;
585 mDoPackageManager = false;
586 }
587 if (doPackageManager) {
588 // The package manager doesn't have a proper <application> etc, but since
589 // it's running here in the system process we can just set up its agent
590 // directly and use a synthetic BackupRequest.
591 if (DEBUG) Log.i(TAG, "Running PM backup pass as well");
592
593 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -0700594 mPackageManager, allAgentPackages());
Christopher Tate6785dd82009-06-18 15:58:25 -0700595 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
596 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
597 processOneBackup(pmRequest,
598 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
599 mTransport);
600 }
601
602 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700603 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700604
605 // Finally, tear down the transport
606 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700607 if (!mTransport.finishBackup()) {
608 // STOPSHIP TODO: handle errors
609 Log.e(TAG, "Backup failure in finishBackup()");
610 }
611 } catch (RemoteException e) {
612 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700613 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700614
615 if (!mJournal.delete()) {
616 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
617 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700618 }
619
620 private void doQueuedBackups(IBackupTransport transport) {
621 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700622 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700623
624 IBackupAgent agent = null;
625 int mode = (request.fullBackup)
626 ? IApplicationThread.BACKUP_MODE_FULL
627 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
628 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700629 agent = bindToAgentSynchronous(request.appInfo, mode);
630 if (agent != null) {
631 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700632 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700633
634 // unbind even on timeout, just in case
635 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700636 } catch (SecurityException ex) {
637 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700638 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700639 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700640 Log.v(TAG, "bind/backup threw");
641 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700642 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700643
Christopher Tate043dadc2009-06-02 16:11:00 -0700644 }
645 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700646
647 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
648 final String packageName = request.appInfo.packageName;
649 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
650
651 try {
652 // Look up the package info & signatures. This is first so that if it
653 // throws an exception, there's no file setup yet that would need to
654 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700655 PackageInfo packInfo;
656 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
657 // The metadata 'package' is synthetic
658 packInfo = new PackageInfo();
659 packInfo.packageName = packageName;
660 } else {
661 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700662 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700663 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700664
665 // !!! TODO: get the state file dir from the transport
666 File savedStateName = new File(mStateDir, packageName);
667 File backupDataName = new File(mDataDir, packageName + ".data");
668 File newStateName = new File(mStateDir, packageName + ".new");
669
670 // In a full backup, we pass a null ParcelFileDescriptor as
671 // the saved-state "file"
672 ParcelFileDescriptor savedState = (request.fullBackup) ? null
673 : ParcelFileDescriptor.open(savedStateName,
674 ParcelFileDescriptor.MODE_READ_ONLY |
675 ParcelFileDescriptor.MODE_CREATE);
676
677 backupDataName.delete();
678 ParcelFileDescriptor backupData =
679 ParcelFileDescriptor.open(backupDataName,
680 ParcelFileDescriptor.MODE_READ_WRITE |
681 ParcelFileDescriptor.MODE_CREATE);
682
683 newStateName.delete();
684 ParcelFileDescriptor newState =
685 ParcelFileDescriptor.open(newStateName,
686 ParcelFileDescriptor.MODE_READ_WRITE |
687 ParcelFileDescriptor.MODE_CREATE);
688
689 // Run the target's backup pass
690 boolean success = false;
691 try {
692 agent.doBackup(savedState, backupData, newState);
693 success = true;
694 } finally {
695 if (savedState != null) {
696 savedState.close();
697 }
698 backupData.close();
699 newState.close();
700 }
701
702 // Now propagate the newly-backed-up data to the transport
703 if (success) {
704 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
705 backupData =
706 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700707 if (!transport.performBackup(packInfo, backupData)) {
708 // STOPSHIP TODO: handle errors
709 Log.e(TAG, "Backup failure in performBackup()");
710 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700711
712 // !!! TODO: After successful transport, delete the now-stale data
713 // and juggle the files so that next time the new state is passed
714 //backupDataName.delete();
715 newStateName.renameTo(savedStateName);
716 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700717 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700718 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700719 }
720 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700721 }
722
Christopher Tatedf01dea2009-06-09 20:45:02 -0700723
724 // ----- Restore handling -----
725
Christopher Tateabce4e82009-06-18 18:35:32 -0700726 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700727 // Allow unsigned apps, but not signed on one device and unsigned on the other
728 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700729 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
730 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700731 if ((storedSigs == null || storedSigs.length == 0)
732 && (deviceSigs == null || deviceSigs.length == 0)) {
733 return true;
734 }
735 if (storedSigs == null || deviceSigs == null) {
736 return false;
737 }
738
Christopher Tateabce4e82009-06-18 18:35:32 -0700739 // !!! TODO: this demands that every stored signature match one
740 // that is present on device, and does not demand the converse.
741 // Is this this right policy?
742 int nStored = storedSigs.length;
743 int nDevice = deviceSigs.length;
744
745 for (int i=0; i < nStored; i++) {
746 boolean match = false;
747 for (int j=0; j < nDevice; j++) {
748 if (storedSigs[i].equals(deviceSigs[j])) {
749 match = true;
750 break;
751 }
752 }
753 if (!match) {
754 return false;
755 }
756 }
757 return true;
758 }
759
Christopher Tatedf01dea2009-06-09 20:45:02 -0700760 class PerformRestoreThread extends Thread {
761 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700762 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700763 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700764
Christopher Tate5cbbf562009-06-22 16:44:51 -0700765 class RestoreRequest {
766 public PackageInfo app;
767 public int storedAppVersion;
768
769 RestoreRequest(PackageInfo _app, int _version) {
770 app = _app;
771 storedAppVersion = _version;
772 }
773 }
774
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700775 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700776 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700777 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700778 }
779
780 @Override
781 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700782 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700783 /**
784 * Restore sequence:
785 *
Dan Egnorefe52642009-06-24 00:16:33 -0700786 * 1. get the restore set description for our identity
787 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700788 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700789 * 3. for each app in the restore queue:
790 * 3.a. clear the app data
791 * 3.b. get the restore data for the app from the transport
792 * 3.c. launch the backup agent for the app
793 * 3.d. agent.doRestore() with the data from the server
794 * 3.e. unbind the agent [and kill the app?]
795 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700796 */
797
Dan Egnorefe52642009-06-24 00:16:33 -0700798 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700799 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700800 RestoreSet[] images = mTransport.getAvailableRestoreSets();
801 if (images == null) {
802 // STOPSHIP TODO: Handle the failure somehow?
803 Log.e(TAG, "Error getting restore sets");
804 return;
805 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700806
Dan Egnorefe52642009-06-24 00:16:33 -0700807 if (images.length == 0) {
808 Log.i(TAG, "No restore sets available");
809 return;
810 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700811
Dan Egnorefe52642009-06-24 00:16:33 -0700812 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700813
Dan Egnorefe52642009-06-24 00:16:33 -0700814 // Get the list of all packages which have backup enabled.
815 // (Include the Package Manager metadata pseudo-package first.)
816 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
817 PackageInfo omPackage = new PackageInfo();
818 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
819 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700820
Dan Egnorefe52642009-06-24 00:16:33 -0700821 List<PackageInfo> agentPackages = allAgentPackages();
822 restorePackages.addAll(agentPackages);
823
824 // STOPSHIP TODO: pick out the set for this token (instead of images[0])
825 long token = images[0].token;
826 if (!mTransport.startRestore(token, restorePackages.toArray(new PackageInfo[0]))) {
827 // STOPSHIP TODO: Handle the failure somehow?
828 Log.e(TAG, "Error starting restore operation");
829 return;
830 }
831
832 String packageName = mTransport.nextRestorePackage();
833 if (packageName == null) {
834 // STOPSHIP TODO: Handle the failure somehow?
835 Log.e(TAG, "Error getting first restore package");
836 return;
837 } else if (packageName.equals("")) {
838 Log.i(TAG, "No restore data available");
839 return;
840 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
841 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
842 + "\", found only \"" + packageName + "\"");
843 return;
844 }
845
846 // Pull the Package Manager metadata from the restore set first
847 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
848 mPackageManager, agentPackages);
849 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
850
851 for (;;) {
852 packageName = mTransport.nextRestorePackage();
853 if (packageName == null) {
854 // STOPSHIP TODO: Handle the failure somehow?
855 Log.e(TAG, "Error getting next restore package");
856 return;
857 } else if (packageName.equals("")) {
858 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700859 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700860
Dan Egnorefe52642009-06-24 00:16:33 -0700861 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
862 if (metaInfo == null) {
863 Log.e(TAG, "Missing metadata for " + packageName);
864 continue;
865 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700866
Dan Egnorefe52642009-06-24 00:16:33 -0700867 int flags = PackageManager.GET_SIGNATURES;
868 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
869 if (metaInfo.versionCode > packageInfo.versionCode) {
870 Log.w(TAG, "Package " + packageName
871 + " restore version [" + metaInfo.versionCode
872 + "] is too new for installed version ["
873 + packageInfo.versionCode + "]");
874 continue;
875 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700876
Dan Egnorefe52642009-06-24 00:16:33 -0700877 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
878 Log.w(TAG, "Signature mismatch restoring " + packageName);
879 continue;
880 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700881
Dan Egnorefe52642009-06-24 00:16:33 -0700882 if (DEBUG) Log.v(TAG, "Package " + packageName
883 + " restore version [" + metaInfo.versionCode
884 + "] is compatible with installed version ["
885 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700886
Dan Egnorefe52642009-06-24 00:16:33 -0700887 // Now perform the actual restore
888 clearApplicationDataSynchronous(packageName);
889 IBackupAgent agent = bindToAgentSynchronous(
890 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700891 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700892 if (agent == null) {
893 Log.w(TAG, "Can't find backup agent for " + packageName);
894 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700895 }
896
Dan Egnorefe52642009-06-24 00:16:33 -0700897 try {
898 processOneRestore(packageInfo, metaInfo.versionCode, agent);
899 } finally {
900 // unbind even on timeout or failure, just in case
901 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
902 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700903 }
Dan Egnorefe52642009-06-24 00:16:33 -0700904 } catch (NameNotFoundException e) {
905 // STOPSHIP TODO: Handle the failure somehow?
906 Log.e(TAG, "Invalid paackage restoring data", e);
907 } catch (RemoteException e) {
908 // STOPSHIP TODO: Handle the failure somehow?
909 Log.e(TAG, "Error restoring data", e);
910 } finally {
911 try {
912 mTransport.finishRestore();
913 } catch (RemoteException e) {
914 Log.e(TAG, "Error finishing restore", e);
915 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700916 }
917 }
918
Dan Egnorefe52642009-06-24 00:16:33 -0700919 // Do the guts of a restore of one application, using mTransport.getRestoreData().
920 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700921 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700922 final String packageName = app.packageName;
923
924 // !!! TODO: get the dirs from the transport
925 File backupDataName = new File(mDataDir, packageName + ".restore");
926 backupDataName.delete();
927 try {
928 ParcelFileDescriptor backupData =
929 ParcelFileDescriptor.open(backupDataName,
930 ParcelFileDescriptor.MODE_READ_WRITE |
931 ParcelFileDescriptor.MODE_CREATE);
932
933 // Run the transport's restore pass
934 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -0700935 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700936 if (!mTransport.getRestoreData(backupData)) {
937 // STOPSHIP TODO: Handle this error somehow?
938 Log.e(TAG, "Error getting restore data for " + packageName);
939 return;
940 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700941 } finally {
942 backupData.close();
943 }
944
945 // Okay, we have the data. Now have the agent do the restore.
946 File newStateName = new File(mStateDir, packageName + ".new");
947 ParcelFileDescriptor newState =
948 ParcelFileDescriptor.open(newStateName,
949 ParcelFileDescriptor.MODE_READ_WRITE |
950 ParcelFileDescriptor.MODE_CREATE);
951
952 backupData = ParcelFileDescriptor.open(backupDataName,
953 ParcelFileDescriptor.MODE_READ_ONLY);
954
Christopher Tatec7b31e32009-06-10 15:49:30 -0700955 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700956 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700957 } finally {
958 newState.close();
959 backupData.close();
960 }
961
962 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -0700963 File savedStateName = new File(mStateDir, packageName);
964 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700965 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700966 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700967 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700968 }
969 }
970
971
Christopher Tate487529a2009-04-29 14:03:25 -0700972 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700973
Christopher Tatea8bf8152009-04-30 11:36:21 -0700974 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700975 // Record that we need a backup pass for the caller. Since multiple callers
976 // may share a uid, we need to note all candidates within that uid and schedule
977 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700978
979 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700980
981 // If the caller does not hold the BACKUP permission, it can only request a
982 // backup of its own data.
983 HashSet<ApplicationInfo> targets;
984 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
985 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
986 targets = mBackupParticipants.get(Binder.getCallingUid());
987 } else {
988 // a caller with full permission can ask to back up any participating app
989 // !!! TODO: allow backup of ANY app?
990 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
991 targets = new HashSet<ApplicationInfo>();
992 int N = mBackupParticipants.size();
993 for (int i = 0; i < N; i++) {
994 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
995 if (s != null) {
996 targets.addAll(s);
997 }
998 }
999 }
Christopher Tate487529a2009-04-29 14:03:25 -07001000 if (targets != null) {
1001 synchronized (mQueueLock) {
1002 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001003 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001004 // validate the caller-supplied package name against the known set of
1005 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001006 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001007 // Add the caller to the set of pending backups. If there is
1008 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001009 BackupRequest req = new BackupRequest(app, false);
1010 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001011
1012 // Journal this request in case of crash
1013 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001014 }
1015 }
1016
Christopher Tate181fafa2009-05-14 11:12:14 -07001017 if (DEBUG) {
1018 int numKeys = mPendingBackups.size();
1019 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1020 for (BackupRequest b : mPendingBackups.values()) {
1021 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1022 }
1023 }
Christopher Tate487529a2009-04-29 14:03:25 -07001024 // Schedule a backup pass in a few minutes. As backup-eligible data
1025 // keeps changing, continue to defer the backup pass until things
1026 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001027 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001028 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001029 } else {
1030 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001031 }
1032 }
Christopher Tate46758122009-05-06 11:22:00 -07001033
Christopher Tatecde87f42009-06-12 12:55:53 -07001034 private void writeToJournalLocked(String str) {
1035 if (mJournalStream != null) {
1036 try {
1037 mJournalStream.writeUTF(str);
1038 } catch (IOException e) {
1039 Log.e(TAG, "Error writing to backup journal");
1040 mJournalStream = null;
1041 mJournal = null;
1042 }
1043 }
1044 }
1045
Christopher Tateace7f092009-06-15 18:07:25 -07001046 // Run a backup pass immediately for any applications that have declared
1047 // that they have pending updates.
1048 public void backupNow() throws RemoteException {
1049 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001050
Christopher Tateace7f092009-06-15 18:07:25 -07001051 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001052 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001053 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001054 }
1055 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001056
Christopher Tateace7f092009-06-15 18:07:25 -07001057 // Report the currently active transport
1058 public int getCurrentTransport() {
1059 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001060 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001061 return mTransportId;
1062 }
1063
Christopher Tate043dadc2009-06-02 16:11:00 -07001064 // Select which transport to use for the next backup operation
1065 public int selectBackupTransport(int transportId) {
1066 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1067
Dan Egnor87a02bc2009-06-17 02:30:10 -07001068 int prevTransport = mTransportId;
1069 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001070 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001071 return prevTransport;
1072 }
1073
1074 // Callback: a requested backup agent has been instantiated. This should only
1075 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001076 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001077 synchronized(mAgentConnectLock) {
1078 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1079 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1080 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1081 mConnectedAgent = agent;
1082 mConnecting = false;
1083 } else {
1084 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1085 + " claiming agent connected");
1086 }
1087 mAgentConnectLock.notifyAll();
1088 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001089 }
1090
1091 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1092 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001093 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001094 public void agentDisconnected(String packageName) {
1095 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001096 synchronized(mAgentConnectLock) {
1097 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1098 mConnectedAgent = null;
1099 mConnecting = false;
1100 } else {
1101 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1102 + " claiming agent disconnected");
1103 }
1104 mAgentConnectLock.notifyAll();
1105 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001106 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001107
Christopher Tate8c850b72009-06-07 19:33:20 -07001108 // Hand off a restore session
1109 public IRestoreSession beginRestoreSession(int transportID) {
1110 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001111
1112 synchronized(this) {
1113 if (mActiveRestoreSession != null) {
1114 Log.d(TAG, "Restore session requested but one already active");
1115 return null;
1116 }
1117 mActiveRestoreSession = new RestoreSession(transportID);
1118 }
1119 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001120 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001121
Christopher Tate9b3905c2009-06-08 15:24:01 -07001122 // ----- Restore session -----
1123
1124 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001125 private static final String TAG = "RestoreSession";
1126
Christopher Tate9b3905c2009-06-08 15:24:01 -07001127 private IBackupTransport mRestoreTransport = null;
1128 RestoreSet[] mRestoreSets = null;
1129
1130 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001131 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001132 }
1133
1134 // --- Binder interface ---
1135 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001136 mContext.enforceCallingPermission("android.permission.BACKUP",
1137 "getAvailableRestoreSets");
1138
Christopher Tatef68eb502009-06-16 11:02:01 -07001139 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001140 synchronized(this) {
1141 if (mRestoreSets == null) {
1142 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1143 }
1144 return mRestoreSets;
1145 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001146 } catch (RuntimeException e) {
1147 Log.d(TAG, "getAvailableRestoreSets exception");
1148 e.printStackTrace();
1149 throw e;
1150 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001151 }
1152
1153 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001154 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1155
1156 if (mRestoreSets != null) {
1157 for (int i = 0; i < mRestoreSets.length; i++) {
1158 if (token == mRestoreSets[i].token) {
1159 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1160 mRestoreTransport);
1161 msg.arg1 = token;
1162 mBackupHandler.sendMessage(msg);
1163 return 0;
1164 }
1165 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001166 } else {
1167 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001168 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001169 return -1;
1170 }
1171
1172 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001173 mContext.enforceCallingPermission("android.permission.BACKUP",
1174 "endRestoreSession");
1175
Dan Egnorefe52642009-06-24 00:16:33 -07001176 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001177 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001178 synchronized(BackupManagerService.this) {
1179 if (BackupManagerService.this.mActiveRestoreSession == this) {
1180 BackupManagerService.this.mActiveRestoreSession = null;
1181 } else {
1182 Log.e(TAG, "ending non-current restore session");
1183 }
1184 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001185 }
1186 }
1187
Christopher Tate043dadc2009-06-02 16:11:00 -07001188
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001189 @Override
1190 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1191 synchronized (mQueueLock) {
1192 int N = mBackupParticipants.size();
1193 pw.println("Participants:");
1194 for (int i=0; i<N; i++) {
1195 int uid = mBackupParticipants.keyAt(i);
1196 pw.print(" uid: ");
1197 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001198 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1199 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001200 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001201 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001202 }
1203 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001204 pw.println("Pending: " + mPendingBackups.size());
1205 for (BackupRequest req : mPendingBackups.values()) {
1206 pw.print(" ");
1207 pw.println(req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001208 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001209 }
1210 }
Christopher Tate487529a2009-04-29 14:03:25 -07001211}