blob: c60f98123d9047b7b5f0b25d0eb615ec22094323 [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);
Christopher Tate181fafa2009-05-14 11:12:14 -0700354 List<ApplicationInfo> targetApps = allAgentApps();
355 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,
359 List<ApplicationInfo> targetApps) {
360 if (DEBUG) {
361 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
362 for (ApplicationInfo a : targetApps) {
363 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
364 }
365 }
366
367 for (ApplicationInfo app : targetApps) {
368 if (packageName == null || app.packageName.equals(packageName)) {
369 int uid = app.uid;
370 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 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700375 set.add(app);
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);
Christopher Tate181fafa2009-05-14 11:12:14 -0700385 List<ApplicationInfo> allApps = null;
386 if (packageName != null) {
387 allApps = new ArrayList<ApplicationInfo>();
388 try {
389 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
390 allApps.add(app);
391 } catch (Exception e) {
392 // just skip it
393 }
394 } else {
395 // all apps with agents
396 allApps = allAgentApps();
397 }
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,
Christopher Tate181fafa2009-05-14 11:12:14 -0700402 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700403 if (DEBUG) {
404 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
405 + ") removing " + agents.size() + " entries");
406 for (ApplicationInfo a : agents) {
407 Log.v(TAG, " - " + a);
408 }
409 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700410 for (ApplicationInfo app : agents) {
411 if (packageName == null || app.packageName.equals(packageName)) {
412 int uid = app.uid;
413 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) {
418 if (entry.packageName.equals(app.packageName)) {
419 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) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700425 mBackupParticipants.delete(uid); }
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
432 private List<ApplicationInfo> allAgentApps() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700433 // !!! TODO: cache this and regenerate only when necessary
Christopher Tate181fafa2009-05-14 11:12:14 -0700434 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
435 int N = allApps.size();
436 if (N > 0) {
437 for (int a = N-1; a >= 0; a--) {
438 ApplicationInfo app = allApps.get(a);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700439 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
440 || app.backupAgentName == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700441 allApps.remove(a);
442 }
443 }
444 }
445 return allApps;
446 }
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
Christopher Tate181fafa2009-05-14 11:12:14 -0700458 List<ApplicationInfo> allApps = allAgentApps();
459 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
Christopher Tatedf01dea2009-06-09 20:45:02 -0700581 // start up the transport
582 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700583 mTransport.startSession();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700584 } catch (Exception e) {
585 Log.e(TAG, "Error session transport");
586 e.printStackTrace();
587 return;
588 }
589
Christopher Tate6785dd82009-06-18 15:58:25 -0700590 // The transport is up and running. First, back up the package manager
591 // metadata if necessary
592 boolean doPackageManager;
593 synchronized (BackupManagerService.this) {
594 doPackageManager = mDoPackageManager;
595 mDoPackageManager = false;
596 }
597 if (doPackageManager) {
598 // The package manager doesn't have a proper <application> etc, but since
599 // it's running here in the system process we can just set up its agent
600 // directly and use a synthetic BackupRequest.
601 if (DEBUG) Log.i(TAG, "Running PM backup pass as well");
602
603 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
604 mPackageManager, allAgentApps());
605 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
606 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
607 processOneBackup(pmRequest,
608 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
609 mTransport);
610 }
611
612 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700613 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700614
615 // Finally, tear down the transport
616 try {
Christopher Tateaa088442009-06-16 18:25:46 -0700617 mTransport.endSession();
Christopher Tate043dadc2009-06-02 16:11:00 -0700618 } catch (Exception e) {
619 Log.e(TAG, "Error ending transport");
620 e.printStackTrace();
621 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700622
623 if (!mJournal.delete()) {
624 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
625 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700626 }
627
628 private void doQueuedBackups(IBackupTransport transport) {
629 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700630 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700631
632 IBackupAgent agent = null;
633 int mode = (request.fullBackup)
634 ? IApplicationThread.BACKUP_MODE_FULL
635 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
636 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700637 agent = bindToAgentSynchronous(request.appInfo, mode);
638 if (agent != null) {
639 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700640 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700641
642 // unbind even on timeout, just in case
643 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700644 } catch (SecurityException ex) {
645 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700646 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700647 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700648 Log.v(TAG, "bind/backup threw");
649 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700650 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700651
Christopher Tate043dadc2009-06-02 16:11:00 -0700652 }
653 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700654
655 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
656 final String packageName = request.appInfo.packageName;
657 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
658
659 try {
660 // Look up the package info & signatures. This is first so that if it
661 // throws an exception, there's no file setup yet that would need to
662 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700663 PackageInfo packInfo;
664 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
665 // The metadata 'package' is synthetic
666 packInfo = new PackageInfo();
667 packInfo.packageName = packageName;
668 } else {
669 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700670 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700671 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700672
673 // !!! TODO: get the state file dir from the transport
674 File savedStateName = new File(mStateDir, packageName);
675 File backupDataName = new File(mDataDir, packageName + ".data");
676 File newStateName = new File(mStateDir, packageName + ".new");
677
678 // In a full backup, we pass a null ParcelFileDescriptor as
679 // the saved-state "file"
680 ParcelFileDescriptor savedState = (request.fullBackup) ? null
681 : ParcelFileDescriptor.open(savedStateName,
682 ParcelFileDescriptor.MODE_READ_ONLY |
683 ParcelFileDescriptor.MODE_CREATE);
684
685 backupDataName.delete();
686 ParcelFileDescriptor backupData =
687 ParcelFileDescriptor.open(backupDataName,
688 ParcelFileDescriptor.MODE_READ_WRITE |
689 ParcelFileDescriptor.MODE_CREATE);
690
691 newStateName.delete();
692 ParcelFileDescriptor newState =
693 ParcelFileDescriptor.open(newStateName,
694 ParcelFileDescriptor.MODE_READ_WRITE |
695 ParcelFileDescriptor.MODE_CREATE);
696
697 // Run the target's backup pass
698 boolean success = false;
699 try {
700 agent.doBackup(savedState, backupData, newState);
701 success = true;
702 } finally {
703 if (savedState != null) {
704 savedState.close();
705 }
706 backupData.close();
707 newState.close();
708 }
709
710 // Now propagate the newly-backed-up data to the transport
711 if (success) {
712 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
713 backupData =
714 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
715 int error = transport.performBackup(packInfo, backupData);
716
717 // !!! TODO: After successful transport, delete the now-stale data
718 // and juggle the files so that next time the new state is passed
719 //backupDataName.delete();
720 newStateName.renameTo(savedStateName);
721 }
722 } catch (NameNotFoundException e) {
723 Log.e(TAG, "Package not found on backup: " + packageName);
724 } catch (FileNotFoundException fnf) {
725 Log.w(TAG, "File not found on backup: ");
726 fnf.printStackTrace();
727 } catch (RemoteException e) {
728 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
729 e.printStackTrace();
730 } catch (Exception e) {
731 Log.w(TAG, "Final exception guard in backup: ");
732 e.printStackTrace();
733 }
734 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700735 }
736
Christopher Tatedf01dea2009-06-09 20:45:02 -0700737
738 // ----- Restore handling -----
739
740 // Is the given package restorable on this device? Returns the on-device app's
741 // ApplicationInfo struct if it is; null if not.
742 //
743 // !!! TODO: also consider signatures
Christopher Tatec7b31e32009-06-10 15:49:30 -0700744 PackageInfo isRestorable(PackageInfo packageInfo) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700745 if (packageInfo.packageName != null) {
746 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700747 PackageInfo app = mPackageManager.getPackageInfo(packageInfo.packageName,
Christopher Tatedf01dea2009-06-09 20:45:02 -0700748 PackageManager.GET_SIGNATURES);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700749 if ((app.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700750 return app;
751 }
752 } catch (Exception e) {
753 // doesn't exist on this device, or other error -- just ignore it.
754 }
755 }
756 return null;
757 }
758
Christopher Tateabce4e82009-06-18 18:35:32 -0700759 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700760 // Allow unsigned apps, but not signed on one device and unsigned on the other
761 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700762 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
763 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700764 if ((storedSigs == null || storedSigs.length == 0)
765 && (deviceSigs == null || deviceSigs.length == 0)) {
766 return true;
767 }
768 if (storedSigs == null || deviceSigs == null) {
769 return false;
770 }
771
Christopher Tateabce4e82009-06-18 18:35:32 -0700772 // !!! TODO: this demands that every stored signature match one
773 // that is present on device, and does not demand the converse.
774 // Is this this right policy?
775 int nStored = storedSigs.length;
776 int nDevice = deviceSigs.length;
777
778 for (int i=0; i < nStored; i++) {
779 boolean match = false;
780 for (int j=0; j < nDevice; j++) {
781 if (storedSigs[i].equals(deviceSigs[j])) {
782 match = true;
783 break;
784 }
785 }
786 if (!match) {
787 return false;
788 }
789 }
790 return true;
791 }
792
Christopher Tatedf01dea2009-06-09 20:45:02 -0700793 class PerformRestoreThread extends Thread {
794 private IBackupTransport mTransport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700795 private int mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700796 private RestoreSet mImage;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700797
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700798 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700799 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700800 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700801 }
802
803 @Override
804 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700805 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700806 /**
807 * Restore sequence:
808 *
809 * 1. start up the transport session
810 * 2. get the restore set description for our identity
811 * 3. for each app in the restore set:
812 * 3.a. if it's restorable on this device, add it to the restore queue
813 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700814 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700815 * 4.b. get the restore data for the app from the transport
816 * 4.c. launch the backup agent for the app
817 * 4.d. agent.doRestore() with the data from the server
818 * 4.e. unbind the agent [and kill the app?]
819 * 5. shut down the transport
820 */
821
822 int err = -1;
823 try {
824 err = mTransport.startSession();
825 } catch (Exception e) {
826 Log.e(TAG, "Error starting transport for restore");
827 e.printStackTrace();
828 }
829
830 if (err == 0) {
831 // build the set of apps to restore
832 try {
833 RestoreSet[] images = mTransport.getAvailableRestoreSets();
834 if (images.length > 0) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700835 // !!! TODO: pick out the set for this token
Christopher Tatec7b31e32009-06-10 15:49:30 -0700836 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700837
Christopher Tateabce4e82009-06-18 18:35:32 -0700838 // Pull the Package Manager metadata from the restore set first
839 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
840 mPackageManager, allAgentApps());
841 PackageInfo pmApp = new PackageInfo();
842 pmApp.packageName = PACKAGE_MANAGER_SENTINEL;
843 processOneRestore(pmApp, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
844
Christopher Tatedf01dea2009-06-09 20:45:02 -0700845 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700846 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
847 HashSet<PackageInfo> appsToRestore = new HashSet<PackageInfo>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700848 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700849 // get the real PackageManager idea of the package
850 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700851 if (app != null) {
Christopher Tateabce4e82009-06-18 18:35:32 -0700852 // Validate against the backed-up signature block, too
Christopher Tate6aa41f42009-06-19 14:14:22 -0700853 Metadata info = pmAgent.getRestoredMetadata(app.packageName);
Christopher Tate3a31a932009-06-22 15:10:30 -0700854 if (info != null) {
855 if (app.versionCode >= info.versionCode) {
856 if (DEBUG) Log.v(TAG, "Restore version "
857 + info.versionCode
858 + " compatible with app version "
859 + app.versionCode);
860 if (signaturesMatch(info.signatures, app.signatures)) {
861 appsToRestore.add(app);
862 } else {
863 Log.w(TAG, "Sig mismatch restoring "
864 + app.packageName);
865 }
Christopher Tate6aa41f42009-06-19 14:14:22 -0700866 } else {
Christopher Tate3a31a932009-06-22 15:10:30 -0700867 Log.i(TAG, "Restore set for " + app.packageName
868 + " is too new [" + info.versionCode
869 + "] for installed app version "
870 + app.versionCode);
Christopher Tate6aa41f42009-06-19 14:14:22 -0700871 }
Christopher Tateabce4e82009-06-18 18:35:32 -0700872 } else {
Christopher Tate3a31a932009-06-22 15:10:30 -0700873 Log.d(TAG, "Unable to get metadata for "
874 + app.packageName);
Christopher Tateabce4e82009-06-18 18:35:32 -0700875 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700876 }
877 }
878
879 // now run the restore queue
880 doQueuedRestores(appsToRestore);
881 }
882 } catch (RemoteException e) {
883 // can't happen; transports run locally
884 }
885
886 // done; shut down the transport
887 try {
888 mTransport.endSession();
889 } catch (Exception e) {
890 Log.e(TAG, "Error ending transport for restore");
891 e.printStackTrace();
892 }
893 }
894
895 // even if the initial session startup failed, report that we're done here
896 }
897
898 // restore each app in the queue
Christopher Tatec7b31e32009-06-10 15:49:30 -0700899 void doQueuedRestores(HashSet<PackageInfo> appsToRestore) {
900 for (PackageInfo app : appsToRestore) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700901 Log.d(TAG, "starting agent for restore of " + app);
902
Christopher Tatedf01dea2009-06-09 20:45:02 -0700903 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700904 // Remove the app's data first
905 clearApplicationDataSynchronous(app.packageName);
906
907 // Now perform the restore into the clean app
908 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
909 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700910 if (agent != null) {
911 processOneRestore(app, agent);
912 }
913
914 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700915 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700916 } catch (SecurityException ex) {
917 // Try for the next one.
918 Log.d(TAG, "error in bind", ex);
919 } catch (RemoteException e) {
920 // can't happen
921 }
922
923 }
924 }
925
Christopher Tatec7b31e32009-06-10 15:49:30 -0700926 // Do the guts of a restore of one application, derived from the 'mImage'
927 // restore set via the 'mTransport' transport.
928 void processOneRestore(PackageInfo app, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700929 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700930 final String packageName = app.packageName;
931
932 // !!! TODO: get the dirs from the transport
933 File backupDataName = new File(mDataDir, packageName + ".restore");
934 backupDataName.delete();
935 try {
936 ParcelFileDescriptor backupData =
937 ParcelFileDescriptor.open(backupDataName,
938 ParcelFileDescriptor.MODE_READ_WRITE |
939 ParcelFileDescriptor.MODE_CREATE);
940
941 // Run the transport's restore pass
942 // Run the target's backup pass
943 int err = -1;
944 try {
945 err = mTransport.getRestoreData(mImage.token, app, backupData);
946 } catch (RemoteException e) {
947 // can't happen
948 } finally {
949 backupData.close();
950 }
951
952 // Okay, we have the data. Now have the agent do the restore.
953 File newStateName = new File(mStateDir, packageName + ".new");
954 ParcelFileDescriptor newState =
955 ParcelFileDescriptor.open(newStateName,
956 ParcelFileDescriptor.MODE_READ_WRITE |
957 ParcelFileDescriptor.MODE_CREATE);
958
959 backupData = ParcelFileDescriptor.open(backupDataName,
960 ParcelFileDescriptor.MODE_READ_ONLY);
961
962 boolean success = false;
963 try {
964 agent.doRestore(backupData, newState);
965 success = true;
966 } catch (Exception e) {
967 Log.e(TAG, "Restore failed for " + packageName);
968 e.printStackTrace();
969 } finally {
970 newState.close();
971 backupData.close();
972 }
973
974 // if everything went okay, remember the recorded state now
975 if (success) {
976 File savedStateName = new File(mStateDir, packageName);
977 newStateName.renameTo(savedStateName);
978 }
979 } catch (FileNotFoundException fnfe) {
980 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
981 } catch (IOException ioe) {
982 Log.e(TAG, "Unable to process restore file: " + ioe);
983 } catch (Exception e) {
984 Log.e(TAG, "Final exception guard in restore:");
985 e.printStackTrace();
986 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700987 }
988 }
989
990
Christopher Tate487529a2009-04-29 14:03:25 -0700991 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -0700992
Christopher Tatea8bf8152009-04-30 11:36:21 -0700993 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700994 // Record that we need a backup pass for the caller. Since multiple callers
995 // may share a uid, we need to note all candidates within that uid and schedule
996 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700997
998 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -0700999
1000 // If the caller does not hold the BACKUP permission, it can only request a
1001 // backup of its own data.
1002 HashSet<ApplicationInfo> targets;
1003 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1004 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1005 targets = mBackupParticipants.get(Binder.getCallingUid());
1006 } else {
1007 // a caller with full permission can ask to back up any participating app
1008 // !!! TODO: allow backup of ANY app?
1009 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1010 targets = new HashSet<ApplicationInfo>();
1011 int N = mBackupParticipants.size();
1012 for (int i = 0; i < N; i++) {
1013 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1014 if (s != null) {
1015 targets.addAll(s);
1016 }
1017 }
1018 }
Christopher Tate487529a2009-04-29 14:03:25 -07001019 if (targets != null) {
1020 synchronized (mQueueLock) {
1021 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001022 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001023 // validate the caller-supplied package name against the known set of
1024 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001025 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001026 // Add the caller to the set of pending backups. If there is
1027 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001028 BackupRequest req = new BackupRequest(app, false);
1029 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001030
1031 // Journal this request in case of crash
1032 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001033 }
1034 }
1035
Christopher Tate181fafa2009-05-14 11:12:14 -07001036 if (DEBUG) {
1037 int numKeys = mPendingBackups.size();
1038 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1039 for (BackupRequest b : mPendingBackups.values()) {
1040 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1041 }
1042 }
Christopher Tate487529a2009-04-29 14:03:25 -07001043 // Schedule a backup pass in a few minutes. As backup-eligible data
1044 // keeps changing, continue to defer the backup pass until things
1045 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001046 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001047 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001048 } else {
1049 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001050 }
1051 }
Christopher Tate46758122009-05-06 11:22:00 -07001052
Christopher Tatecde87f42009-06-12 12:55:53 -07001053 private void writeToJournalLocked(String str) {
1054 if (mJournalStream != null) {
1055 try {
1056 mJournalStream.writeUTF(str);
1057 } catch (IOException e) {
1058 Log.e(TAG, "Error writing to backup journal");
1059 mJournalStream = null;
1060 mJournal = null;
1061 }
1062 }
1063 }
1064
Christopher Tateace7f092009-06-15 18:07:25 -07001065 // Run a backup pass immediately for any applications that have declared
1066 // that they have pending updates.
1067 public void backupNow() throws RemoteException {
1068 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001069
Christopher Tateace7f092009-06-15 18:07:25 -07001070 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001071 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001072 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001073 }
1074 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001075
Christopher Tateace7f092009-06-15 18:07:25 -07001076 // Report the currently active transport
1077 public int getCurrentTransport() {
1078 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001079 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001080 return mTransportId;
1081 }
1082
Christopher Tate043dadc2009-06-02 16:11:00 -07001083 // Select which transport to use for the next backup operation
1084 public int selectBackupTransport(int transportId) {
1085 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1086
Dan Egnor87a02bc2009-06-17 02:30:10 -07001087 int prevTransport = mTransportId;
1088 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001089 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001090 return prevTransport;
1091 }
1092
1093 // Callback: a requested backup agent has been instantiated. This should only
1094 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001095 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001096 synchronized(mAgentConnectLock) {
1097 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1098 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1099 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1100 mConnectedAgent = agent;
1101 mConnecting = false;
1102 } else {
1103 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1104 + " claiming agent connected");
1105 }
1106 mAgentConnectLock.notifyAll();
1107 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001108 }
1109
1110 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1111 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001112 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001113 public void agentDisconnected(String packageName) {
1114 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001115 synchronized(mAgentConnectLock) {
1116 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1117 mConnectedAgent = null;
1118 mConnecting = false;
1119 } else {
1120 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1121 + " claiming agent disconnected");
1122 }
1123 mAgentConnectLock.notifyAll();
1124 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001125 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001126
Christopher Tate8c850b72009-06-07 19:33:20 -07001127 // Hand off a restore session
1128 public IRestoreSession beginRestoreSession(int transportID) {
1129 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001130
1131 synchronized(this) {
1132 if (mActiveRestoreSession != null) {
1133 Log.d(TAG, "Restore session requested but one already active");
1134 return null;
1135 }
1136 mActiveRestoreSession = new RestoreSession(transportID);
1137 }
1138 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001139 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001140
Christopher Tate9b3905c2009-06-08 15:24:01 -07001141 // ----- Restore session -----
1142
1143 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001144 private static final String TAG = "RestoreSession";
1145
Christopher Tate9b3905c2009-06-08 15:24:01 -07001146 private IBackupTransport mRestoreTransport = null;
1147 RestoreSet[] mRestoreSets = null;
1148
1149 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001150 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001151 }
1152
1153 // --- Binder interface ---
1154 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001155 mContext.enforceCallingPermission("android.permission.BACKUP",
1156 "getAvailableRestoreSets");
1157
Christopher Tatef68eb502009-06-16 11:02:01 -07001158 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001159 synchronized(this) {
1160 if (mRestoreSets == null) {
1161 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1162 }
1163 return mRestoreSets;
1164 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001165 } catch (RuntimeException e) {
1166 Log.d(TAG, "getAvailableRestoreSets exception");
1167 e.printStackTrace();
1168 throw e;
1169 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001170 }
1171
1172 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001173 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1174
1175 if (mRestoreSets != null) {
1176 for (int i = 0; i < mRestoreSets.length; i++) {
1177 if (token == mRestoreSets[i].token) {
1178 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1179 mRestoreTransport);
1180 msg.arg1 = token;
1181 mBackupHandler.sendMessage(msg);
1182 return 0;
1183 }
1184 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001185 } else {
1186 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001187 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001188 return -1;
1189 }
1190
1191 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001192 mContext.enforceCallingPermission("android.permission.BACKUP",
1193 "endRestoreSession");
1194
Christopher Tate9b3905c2009-06-08 15:24:01 -07001195 mRestoreTransport.endSession();
1196 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001197 synchronized(BackupManagerService.this) {
1198 if (BackupManagerService.this.mActiveRestoreSession == this) {
1199 BackupManagerService.this.mActiveRestoreSession = null;
1200 } else {
1201 Log.e(TAG, "ending non-current restore session");
1202 }
1203 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001204 }
1205 }
1206
Christopher Tate043dadc2009-06-02 16:11:00 -07001207
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001208 @Override
1209 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1210 synchronized (mQueueLock) {
1211 int N = mBackupParticipants.size();
1212 pw.println("Participants:");
1213 for (int i=0; i<N; i++) {
1214 int uid = mBackupParticipants.keyAt(i);
1215 pw.print(" uid: ");
1216 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001217 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1218 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001219 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001220 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001221 }
1222 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001223 pw.println("Pending: " + mPendingBackups.size());
1224 for (BackupRequest req : mPendingBackups.values()) {
1225 pw.print(" ");
1226 pw.println(req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001227 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001228 }
1229 }
Christopher Tate487529a2009-04-29 14:03:25 -07001230}