blob: 197404e8958865726d84153c0751e835a6b24fe6 [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 Tate5cbbf562009-06-22 16:44:51 -0700798 class RestoreRequest {
799 public PackageInfo app;
800 public int storedAppVersion;
801
802 RestoreRequest(PackageInfo _app, int _version) {
803 app = _app;
804 storedAppVersion = _version;
805 }
806 }
807
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700808 PerformRestoreThread(IBackupTransport transport, int restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700809 mTransport = transport;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700810 mToken = restoreSetToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700811 }
812
813 @Override
814 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700815 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700816 /**
817 * Restore sequence:
818 *
819 * 1. start up the transport session
820 * 2. get the restore set description for our identity
821 * 3. for each app in the restore set:
822 * 3.a. if it's restorable on this device, add it to the restore queue
823 * 4. for each app in the restore queue:
Christopher Tatec7b31e32009-06-10 15:49:30 -0700824 * 4.a. clear the app data
Christopher Tatedf01dea2009-06-09 20:45:02 -0700825 * 4.b. get the restore data for the app from the transport
826 * 4.c. launch the backup agent for the app
827 * 4.d. agent.doRestore() with the data from the server
828 * 4.e. unbind the agent [and kill the app?]
829 * 5. shut down the transport
830 */
831
832 int err = -1;
833 try {
834 err = mTransport.startSession();
835 } catch (Exception e) {
836 Log.e(TAG, "Error starting transport for restore");
837 e.printStackTrace();
838 }
839
840 if (err == 0) {
841 // build the set of apps to restore
842 try {
843 RestoreSet[] images = mTransport.getAvailableRestoreSets();
844 if (images.length > 0) {
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700845 // !!! TODO: pick out the set for this token
Christopher Tatec7b31e32009-06-10 15:49:30 -0700846 mImage = images[0];
Christopher Tatedf01dea2009-06-09 20:45:02 -0700847
Christopher Tateabce4e82009-06-18 18:35:32 -0700848 // Pull the Package Manager metadata from the restore set first
849 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
850 mPackageManager, allAgentApps());
851 PackageInfo pmApp = new PackageInfo();
852 pmApp.packageName = PACKAGE_MANAGER_SENTINEL;
Christopher Tate5cbbf562009-06-22 16:44:51 -0700853 // !!! TODO: version currently ignored when 'restoring' the PM metadata
854 processOneRestore(pmApp, 0,
855 IBackupAgent.Stub.asInterface(pmAgent.onBind()));
Christopher Tateabce4e82009-06-18 18:35:32 -0700856
Christopher Tatedf01dea2009-06-09 20:45:02 -0700857 // build the set of apps we will attempt to restore
Christopher Tatec7b31e32009-06-10 15:49:30 -0700858 PackageInfo[] packages = mTransport.getAppSet(mImage.token);
Christopher Tate5cbbf562009-06-22 16:44:51 -0700859 HashSet<RestoreRequest> appsToRestore = new HashSet<RestoreRequest>();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700860 for (PackageInfo pkg: packages) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700861 // get the real PackageManager idea of the package
862 PackageInfo app = isRestorable(pkg);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700863 if (app != null) {
Christopher Tateabce4e82009-06-18 18:35:32 -0700864 // Validate against the backed-up signature block, too
Christopher Tate6aa41f42009-06-19 14:14:22 -0700865 Metadata info = pmAgent.getRestoredMetadata(app.packageName);
Christopher Tate3a31a932009-06-22 15:10:30 -0700866 if (info != null) {
867 if (app.versionCode >= info.versionCode) {
868 if (DEBUG) Log.v(TAG, "Restore version "
869 + info.versionCode
870 + " compatible with app version "
871 + app.versionCode);
872 if (signaturesMatch(info.signatures, app.signatures)) {
Christopher Tate5cbbf562009-06-22 16:44:51 -0700873 appsToRestore.add(
874 new RestoreRequest(app, info.versionCode));
Christopher Tate3a31a932009-06-22 15:10:30 -0700875 } else {
876 Log.w(TAG, "Sig mismatch restoring "
877 + app.packageName);
878 }
Christopher Tate6aa41f42009-06-19 14:14:22 -0700879 } else {
Christopher Tate3a31a932009-06-22 15:10:30 -0700880 Log.i(TAG, "Restore set for " + app.packageName
881 + " is too new [" + info.versionCode
882 + "] for installed app version "
883 + app.versionCode);
Christopher Tate6aa41f42009-06-19 14:14:22 -0700884 }
Christopher Tateabce4e82009-06-18 18:35:32 -0700885 } else {
Christopher Tate3a31a932009-06-22 15:10:30 -0700886 Log.d(TAG, "Unable to get metadata for "
887 + app.packageName);
Christopher Tateabce4e82009-06-18 18:35:32 -0700888 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700889 }
890 }
891
892 // now run the restore queue
893 doQueuedRestores(appsToRestore);
894 }
895 } catch (RemoteException e) {
896 // can't happen; transports run locally
897 }
898
899 // done; shut down the transport
900 try {
901 mTransport.endSession();
902 } catch (Exception e) {
903 Log.e(TAG, "Error ending transport for restore");
904 e.printStackTrace();
905 }
906 }
907
908 // even if the initial session startup failed, report that we're done here
909 }
910
911 // restore each app in the queue
Christopher Tate5cbbf562009-06-22 16:44:51 -0700912 void doQueuedRestores(HashSet<RestoreRequest> appsToRestore) {
913 for (RestoreRequest req : appsToRestore) {
914 PackageInfo app = req.app;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700915 Log.d(TAG, "starting agent for restore of " + app);
916
Christopher Tatedf01dea2009-06-09 20:45:02 -0700917 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700918 // Remove the app's data first
919 clearApplicationDataSynchronous(app.packageName);
920
921 // Now perform the restore into the clean app
922 IBackupAgent agent = bindToAgentSynchronous(app.applicationInfo,
923 IApplicationThread.BACKUP_MODE_RESTORE);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700924 if (agent != null) {
Christopher Tate5cbbf562009-06-22 16:44:51 -0700925 processOneRestore(app, req.storedAppVersion, agent);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700926 }
927
928 // unbind even on timeout, just in case
Christopher Tatec7b31e32009-06-10 15:49:30 -0700929 mActivityManager.unbindBackupAgent(app.applicationInfo);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700930 } catch (SecurityException ex) {
931 // Try for the next one.
932 Log.d(TAG, "error in bind", ex);
933 } catch (RemoteException e) {
934 // can't happen
935 }
936
937 }
938 }
939
Christopher Tatec7b31e32009-06-10 15:49:30 -0700940 // Do the guts of a restore of one application, derived from the 'mImage'
941 // restore set via the 'mTransport' transport.
Christopher Tate5cbbf562009-06-22 16:44:51 -0700942 void processOneRestore(PackageInfo app, int storedAppVersion, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700943 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -0700944 final String packageName = app.packageName;
945
946 // !!! TODO: get the dirs from the transport
947 File backupDataName = new File(mDataDir, packageName + ".restore");
948 backupDataName.delete();
949 try {
950 ParcelFileDescriptor backupData =
951 ParcelFileDescriptor.open(backupDataName,
952 ParcelFileDescriptor.MODE_READ_WRITE |
953 ParcelFileDescriptor.MODE_CREATE);
954
955 // Run the transport's restore pass
956 // Run the target's backup pass
957 int err = -1;
958 try {
959 err = mTransport.getRestoreData(mImage.token, app, backupData);
960 } catch (RemoteException e) {
961 // can't happen
962 } finally {
963 backupData.close();
964 }
965
966 // Okay, we have the data. Now have the agent do the restore.
967 File newStateName = new File(mStateDir, packageName + ".new");
968 ParcelFileDescriptor newState =
969 ParcelFileDescriptor.open(newStateName,
970 ParcelFileDescriptor.MODE_READ_WRITE |
971 ParcelFileDescriptor.MODE_CREATE);
972
973 backupData = ParcelFileDescriptor.open(backupDataName,
974 ParcelFileDescriptor.MODE_READ_ONLY);
975
976 boolean success = false;
977 try {
Christopher Tate5cbbf562009-06-22 16:44:51 -0700978 agent.doRestore(backupData, storedAppVersion, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700979 success = true;
980 } catch (Exception e) {
981 Log.e(TAG, "Restore failed for " + packageName);
982 e.printStackTrace();
983 } finally {
984 newState.close();
985 backupData.close();
986 }
987
988 // if everything went okay, remember the recorded state now
989 if (success) {
990 File savedStateName = new File(mStateDir, packageName);
991 newStateName.renameTo(savedStateName);
992 }
993 } catch (FileNotFoundException fnfe) {
994 Log.v(TAG, "Couldn't open file for restore: " + fnfe);
995 } catch (IOException ioe) {
996 Log.e(TAG, "Unable to process restore file: " + ioe);
997 } catch (Exception e) {
998 Log.e(TAG, "Final exception guard in restore:");
999 e.printStackTrace();
1000 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001001 }
1002 }
1003
1004
Christopher Tate487529a2009-04-29 14:03:25 -07001005 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001006
Christopher Tatea8bf8152009-04-30 11:36:21 -07001007 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001008 // Record that we need a backup pass for the caller. Since multiple callers
1009 // may share a uid, we need to note all candidates within that uid and schedule
1010 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001011
1012 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001013
1014 // If the caller does not hold the BACKUP permission, it can only request a
1015 // backup of its own data.
1016 HashSet<ApplicationInfo> targets;
1017 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1018 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1019 targets = mBackupParticipants.get(Binder.getCallingUid());
1020 } else {
1021 // a caller with full permission can ask to back up any participating app
1022 // !!! TODO: allow backup of ANY app?
1023 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1024 targets = new HashSet<ApplicationInfo>();
1025 int N = mBackupParticipants.size();
1026 for (int i = 0; i < N; i++) {
1027 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1028 if (s != null) {
1029 targets.addAll(s);
1030 }
1031 }
1032 }
Christopher Tate487529a2009-04-29 14:03:25 -07001033 if (targets != null) {
1034 synchronized (mQueueLock) {
1035 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001036 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001037 // validate the caller-supplied package name against the known set of
1038 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001039 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001040 // Add the caller to the set of pending backups. If there is
1041 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001042 BackupRequest req = new BackupRequest(app, false);
1043 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001044
1045 // Journal this request in case of crash
1046 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001047 }
1048 }
1049
Christopher Tate181fafa2009-05-14 11:12:14 -07001050 if (DEBUG) {
1051 int numKeys = mPendingBackups.size();
1052 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
1053 for (BackupRequest b : mPendingBackups.values()) {
1054 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1055 }
1056 }
Christopher Tate487529a2009-04-29 14:03:25 -07001057 // Schedule a backup pass in a few minutes. As backup-eligible data
1058 // keeps changing, continue to defer the backup pass until things
1059 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001060 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001061 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001062 } else {
1063 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001064 }
1065 }
Christopher Tate46758122009-05-06 11:22:00 -07001066
Christopher Tatecde87f42009-06-12 12:55:53 -07001067 private void writeToJournalLocked(String str) {
1068 if (mJournalStream != null) {
1069 try {
1070 mJournalStream.writeUTF(str);
1071 } catch (IOException e) {
1072 Log.e(TAG, "Error writing to backup journal");
1073 mJournalStream = null;
1074 mJournal = null;
1075 }
1076 }
1077 }
1078
Christopher Tateace7f092009-06-15 18:07:25 -07001079 // Run a backup pass immediately for any applications that have declared
1080 // that they have pending updates.
1081 public void backupNow() throws RemoteException {
1082 mContext.enforceCallingPermission("android.permission.BACKUP", "tryBackupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001083
Christopher Tateace7f092009-06-15 18:07:25 -07001084 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001085 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001086 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001087 }
1088 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001089
Christopher Tateace7f092009-06-15 18:07:25 -07001090 // Report the currently active transport
1091 public int getCurrentTransport() {
1092 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
Christopher Tateabce4e82009-06-18 18:35:32 -07001093 Log.v(TAG, "getCurrentTransport() returning " + mTransportId);
Christopher Tateace7f092009-06-15 18:07:25 -07001094 return mTransportId;
1095 }
1096
Christopher Tate043dadc2009-06-02 16:11:00 -07001097 // Select which transport to use for the next backup operation
1098 public int selectBackupTransport(int transportId) {
1099 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1100
Dan Egnor87a02bc2009-06-17 02:30:10 -07001101 int prevTransport = mTransportId;
1102 mTransportId = transportId;
Christopher Tateabce4e82009-06-18 18:35:32 -07001103 Log.v(TAG, "selectBackupTransport() set " + mTransportId + " returning " + prevTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -07001104 return prevTransport;
1105 }
1106
1107 // Callback: a requested backup agent has been instantiated. This should only
1108 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001109 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001110 synchronized(mAgentConnectLock) {
1111 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1112 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1113 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1114 mConnectedAgent = agent;
1115 mConnecting = false;
1116 } else {
1117 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1118 + " claiming agent connected");
1119 }
1120 mAgentConnectLock.notifyAll();
1121 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001122 }
1123
1124 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1125 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001126 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001127 public void agentDisconnected(String packageName) {
1128 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001129 synchronized(mAgentConnectLock) {
1130 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1131 mConnectedAgent = null;
1132 mConnecting = false;
1133 } else {
1134 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1135 + " claiming agent disconnected");
1136 }
1137 mAgentConnectLock.notifyAll();
1138 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001139 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001140
Christopher Tate8c850b72009-06-07 19:33:20 -07001141 // Hand off a restore session
1142 public IRestoreSession beginRestoreSession(int transportID) {
1143 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001144
1145 synchronized(this) {
1146 if (mActiveRestoreSession != null) {
1147 Log.d(TAG, "Restore session requested but one already active");
1148 return null;
1149 }
1150 mActiveRestoreSession = new RestoreSession(transportID);
1151 }
1152 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001153 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001154
Christopher Tate9b3905c2009-06-08 15:24:01 -07001155 // ----- Restore session -----
1156
1157 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001158 private static final String TAG = "RestoreSession";
1159
Christopher Tate9b3905c2009-06-08 15:24:01 -07001160 private IBackupTransport mRestoreTransport = null;
1161 RestoreSet[] mRestoreSets = null;
1162
1163 RestoreSession(int transportID) {
Dan Egnor87a02bc2009-06-17 02:30:10 -07001164 mRestoreTransport = getTransport(transportID);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001165 }
1166
1167 // --- Binder interface ---
1168 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001169 mContext.enforceCallingPermission("android.permission.BACKUP",
1170 "getAvailableRestoreSets");
1171
Christopher Tatef68eb502009-06-16 11:02:01 -07001172 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001173 synchronized(this) {
1174 if (mRestoreSets == null) {
1175 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1176 }
1177 return mRestoreSets;
1178 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001179 } catch (RuntimeException e) {
1180 Log.d(TAG, "getAvailableRestoreSets exception");
1181 e.printStackTrace();
1182 throw e;
1183 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001184 }
1185
1186 public int performRestore(int token) throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001187 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1188
1189 if (mRestoreSets != null) {
1190 for (int i = 0; i < mRestoreSets.length; i++) {
1191 if (token == mRestoreSets[i].token) {
1192 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE,
1193 mRestoreTransport);
1194 msg.arg1 = token;
1195 mBackupHandler.sendMessage(msg);
1196 return 0;
1197 }
1198 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001199 } else {
1200 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001201 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001202 return -1;
1203 }
1204
1205 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001206 mContext.enforceCallingPermission("android.permission.BACKUP",
1207 "endRestoreSession");
1208
Christopher Tate9b3905c2009-06-08 15:24:01 -07001209 mRestoreTransport.endSession();
1210 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001211 synchronized(BackupManagerService.this) {
1212 if (BackupManagerService.this.mActiveRestoreSession == this) {
1213 BackupManagerService.this.mActiveRestoreSession = null;
1214 } else {
1215 Log.e(TAG, "ending non-current restore session");
1216 }
1217 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001218 }
1219 }
1220
Christopher Tate043dadc2009-06-02 16:11:00 -07001221
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001222 @Override
1223 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1224 synchronized (mQueueLock) {
1225 int N = mBackupParticipants.size();
1226 pw.println("Participants:");
1227 for (int i=0; i<N; i++) {
1228 int uid = mBackupParticipants.keyAt(i);
1229 pw.print(" uid: ");
1230 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001231 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1232 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001233 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -07001234 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001235 }
1236 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001237 pw.println("Pending: " + mPendingBackups.size());
1238 for (BackupRequest req : mPendingBackups.values()) {
1239 pw.print(" ");
1240 pw.println(req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001241 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001242 }
1243 }
Christopher Tate487529a2009-04-29 14:03:25 -07001244}