blob: b15c06ba280478f4010bc5c7609830cfa0f246cc [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 Tatece0bf062009-07-01 11:43:53 -070036import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070037import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070038import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070039import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070040import android.os.Handler;
41import android.os.IBinder;
42import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070043import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070044import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070045import android.os.RemoteException;
46import android.util.Log;
47import android.util.SparseArray;
48
49import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070050import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070051import android.backup.IRestoreSession;
Christopher 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 Tatec7b31e32009-06-10 15:49:30 -070063import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070064import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070065import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070066import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040067import java.util.ArrayList;
68import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070069import java.util.HashSet;
70import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070071import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070072
73class BackupManagerService extends IBackupManager.Stub {
74 private static final String TAG = "BackupManagerService";
75 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070076
Christopher Tatece0bf062009-07-01 11:43:53 -070077 // Secure settings
78 private static final String BACKUP_TRANSPORT_SETTING = "backup_transport";
79 private static final String BACKUP_ENABLED_SETTING = "backup_enabled";
Christopher Tate6ef58a12009-06-29 14:56:28 -070080
Christopher Tate49401dd2009-07-01 12:34:29 -070081 // How often we perform a backup pass. Privileged external callers can
82 // trigger an immediate pass.
83 private static final long BACKUP_INTERVAL = 60 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070084
85 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070086 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070087 private static final int MSG_RUN_RESTORE = 3;
Christopher Tatec7b31e32009-06-10 15:49:30 -070088
89 // Timeout interval for deciding that a bind or clear-data has taken too long
90 static final long TIMEOUT_INTERVAL = 10 * 1000;
91
Christopher Tate487529a2009-04-29 14:03:25 -070092 private Context mContext;
93 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -070094 private IActivityManager mActivityManager;
95 private boolean mEnabled; // access to this is synchronized on 'this'
Christopher Tate487529a2009-04-29 14:03:25 -070096 private final BackupHandler mBackupHandler = new BackupHandler();
97 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate6ef58a12009-06-29 14:56:28 -070098 private final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -070099 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700100 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -0700101 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700102 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700103 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700104
Christopher Tate181fafa2009-05-14 11:12:14 -0700105 BackupRequest(ApplicationInfo app, boolean isFull) {
106 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700107 fullBackup = isFull;
108 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700109
110 public String toString() {
111 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
112 }
Christopher Tate46758122009-05-06 11:22:00 -0700113 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400114 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700115 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
116 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700117
118 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate6785dd82009-06-18 15:58:25 -0700119 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700120
121 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700122 private final Object mQueueLock = new Object();
123
Christopher Tate043dadc2009-06-02 16:11:00 -0700124 // The thread performing the sequence of queued backups binds to each app's agent
125 // in succession. Bind notifications are asynchronously delivered through the
126 // Activity Manager; use this lock object to signal when a requested binding has
127 // completed.
128 private final Object mAgentConnectLock = new Object();
129 private IBackupAgent mConnectedAgent;
130 private volatile boolean mConnecting;
131
Christopher Tatec7b31e32009-06-10 15:49:30 -0700132 // A similar synchronicity mechanism around clearing apps' data for restore
133 private final Object mClearDataLock = new Object();
134 private volatile boolean mClearingData;
135
Christopher Tate91717492009-06-26 21:07:13 -0700136 // Transport bookkeeping
Christopher Tate91717492009-06-26 21:07:13 -0700137 private final HashMap<String,IBackupTransport> mTransports
138 = new HashMap<String,IBackupTransport>();
139 private String mCurrentTransport;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700140 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700141 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700142
Christopher Tate7d562ec2009-06-25 18:03:43 -0700143 private class RestoreParams {
144 public IBackupTransport transport;
145 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700146 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700147
Dan Egnor156411d2009-06-26 13:20:02 -0700148 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700149 transport = _transport;
150 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700151 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700152 }
153 }
154
Christopher Tate5cb400b2009-06-25 16:03:14 -0700155 // Where we keep our journal files and other bookkeeping
156 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700157 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700158 private File mJournalDir;
159 private File mJournal;
160 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700161
Christopher Tate487529a2009-04-29 14:03:25 -0700162 public BackupManagerService(Context context) {
163 mContext = context;
164 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700165 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700166
Christopher Tate22b87872009-05-04 16:41:53 -0700167 // Set up our bookkeeping
Christopher Tate6ef58a12009-06-29 14:56:28 -0700168 // !!! STOPSHIP: make this disabled by default so that we then gate on
169 // setupwizard or other opt-out UI
Christopher Tatece0bf062009-07-01 11:43:53 -0700170 mEnabled = (Settings.Secure.getInt(mContext.getContentResolver(),
171 BACKUP_ENABLED_SETTING, 1) != 0);
Christopher Tate5cb400b2009-06-25 16:03:14 -0700172 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700173 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700174
Christopher Tatecde87f42009-06-12 12:55:53 -0700175 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700176 mJournalDir = new File(mBaseStateDir, "pending");
177 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700178 makeJournalLocked(); // okay because no other threads are running yet
179
Christopher Tateabce4e82009-06-18 18:35:32 -0700180 // Build our mapping of uid to backup client services. This implicitly
181 // schedules a backup pass on the Package Manager metadata the first
182 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700183 synchronized (mBackupParticipants) {
184 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700185 }
186
Dan Egnor87a02bc2009-06-17 02:30:10 -0700187 // Set up our transport options and initialize the default transport
188 // TODO: Have transports register themselves somehow?
189 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700190 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700191 ComponentName localName = new ComponentName(context, LocalTransport.class);
192 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700193
Christopher Tate91717492009-06-26 21:07:13 -0700194 mGoogleTransport = null;
195 // !!! TODO: set up the default transport name "the right way"
Christopher Tatece0bf062009-07-01 11:43:53 -0700196 mCurrentTransport = Settings.Secure.getString(mContext.getContentResolver(),
197 BACKUP_TRANSPORT_SETTING);
198 if (mCurrentTransport == null) {
199 mCurrentTransport = "com.google.android.backup/.BackupTransportService";
200 Settings.Secure.putString(mContext.getContentResolver(),
201 BACKUP_TRANSPORT_SETTING, mCurrentTransport);
202 }
Christopher Tate91717492009-06-26 21:07:13 -0700203 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
204
205 // Attach to the Google backup transport. When this comes up, it will set
206 // itself as the current transport because we explicitly reset mCurrentTransport
207 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700208 Intent intent = new Intent().setComponent(new ComponentName(
209 "com.google.android.backup",
210 "com.google.android.backup.BackupTransportService"));
211 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700212
Christopher Tatecde87f42009-06-12 12:55:53 -0700213 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700214 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700215 parseLeftoverJournals();
216
Christopher Tate3799bc22009-05-06 16:13:56 -0700217 // Register for broadcasts about package install, etc., so we can
218 // update the provider list.
219 IntentFilter filter = new IntentFilter();
220 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
221 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
222 filter.addDataScheme("package");
223 mContext.registerReceiver(mBroadcastReceiver, filter);
Christopher Tate49401dd2009-07-01 12:34:29 -0700224
225 // Schedule the first backup pass -- okay because no other threads are
226 // running yet
227 if (mEnabled) {
228 scheduleBackupPassLocked(BACKUP_INTERVAL);
229 }
230}
Christopher Tate3799bc22009-05-06 16:13:56 -0700231
Christopher Tatecde87f42009-06-12 12:55:53 -0700232 private void makeJournalLocked() {
233 try {
234 mJournal = File.createTempFile("journal", null, mJournalDir);
235 mJournalStream = new RandomAccessFile(mJournal, "rwd");
236 } catch (IOException e) {
237 Log.e(TAG, "Unable to write backup journals");
238 mJournal = null;
239 mJournalStream = null;
240 }
241 }
242
243 private void parseLeftoverJournals() {
244 if (mJournal != null) {
245 File[] allJournals = mJournalDir.listFiles();
246 for (File f : allJournals) {
247 if (f.compareTo(mJournal) != 0) {
248 // This isn't the current journal, so it must be a leftover. Read
249 // out the package names mentioned there and schedule them for
250 // backup.
251 try {
252 Log.i(TAG, "Found stale backup journal, scheduling:");
253 RandomAccessFile in = new RandomAccessFile(f, "r");
254 while (true) {
255 String packageName = in.readUTF();
256 Log.i(TAG, " + " + packageName);
257 dataChanged(packageName);
258 }
259 } catch (EOFException e) {
260 // no more data; we're done
261 } catch (Exception e) {
262 // can't read it or other error; just skip it
263 } finally {
264 // close/delete the file
265 f.delete();
266 }
267 }
268 }
269 }
270 }
271
Christopher Tate91717492009-06-26 21:07:13 -0700272 // Add a transport to our set of available backends
273 private void registerTransport(String name, IBackupTransport transport) {
274 synchronized (mTransports) {
275 mTransports.put(name, transport);
276 }
277 }
278
Christopher Tate3799bc22009-05-06 16:13:56 -0700279 // ----- Track installation/removal of packages -----
280 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
281 public void onReceive(Context context, Intent intent) {
282 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
283
284 Uri uri = intent.getData();
285 if (uri == null) {
286 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700287 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700288 String pkgName = uri.getSchemeSpecificPart();
289 if (pkgName == null) {
290 return;
291 }
292
293 String action = intent.getAction();
294 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
295 synchronized (mBackupParticipants) {
296 Bundle extras = intent.getExtras();
297 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
298 // The package was just upgraded
299 updatePackageParticipantsLocked(pkgName);
300 } else {
301 // The package was just added
302 addPackageParticipantsLocked(pkgName);
303 }
304 }
305 }
306 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
307 Bundle extras = intent.getExtras();
308 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
309 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
310 } else {
311 synchronized (mBackupParticipants) {
312 removePackageParticipantsLocked(pkgName);
313 }
314 }
315 }
316 }
317 };
318
Dan Egnor87a02bc2009-06-17 02:30:10 -0700319 // ----- Track connection to GoogleBackupTransport service -----
320 ServiceConnection mGoogleConnection = new ServiceConnection() {
321 public void onServiceConnected(ComponentName name, IBinder service) {
322 if (DEBUG) Log.v(TAG, "Connected to Google transport");
323 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700324 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700325 }
326
327 public void onServiceDisconnected(ComponentName name) {
328 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
329 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700330 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700331 }
332 };
333
Joe Onorato8ad02812009-05-13 01:41:44 -0400334 // ----- Run the actual backup process asynchronously -----
335
Christopher Tate181fafa2009-05-14 11:12:14 -0700336 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400337 public void handleMessage(Message msg) {
338
339 switch (msg.what) {
340 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700341 {
Christopher Tate91717492009-06-26 21:07:13 -0700342 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700343 if (transport == null) {
344 Log.v(TAG, "Backup requested but no transport available");
345 break;
346 }
347
Joe Onorato8ad02812009-05-13 01:41:44 -0400348 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700349 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700350 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400351 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700352 // Do we have any work to do?
353 if (mPendingBackups.size() > 0) {
354 for (BackupRequest b: mPendingBackups.values()) {
355 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700356 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700357 Log.v(TAG, "clearing pending backups");
358 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700359
Christopher Tate49401dd2009-07-01 12:34:29 -0700360 // Start a new backup-queue journal file too
361 if (mJournalStream != null) {
362 try {
363 mJournalStream.close();
364 } catch (IOException e) {
365 // don't need to do anything
366 }
367 makeJournalLocked();
368 }
369
370 // At this point, we have started a new journal file, and the old
371 // file identity is being passed to the backup processing thread.
372 // When it completes successfully, that old journal file will be
373 // deleted. If we crash prior to that, the old journal is parsed
374 // at next boot and the journaled requests fulfilled.
375 (new PerformBackupThread(transport, queue, oldJournal)).start();
376 } else {
377 Log.v(TAG, "Backup requested but nothing pending");
378 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400379 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700380
Christopher Tate49401dd2009-07-01 12:34:29 -0700381 // Schedule the next pass.
382 synchronized (mQueueLock) {
383 scheduleBackupPassLocked(BACKUP_INTERVAL);
384 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700385 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700386 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700387
388 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400389 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700390
391 case MSG_RUN_RESTORE:
392 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700393 RestoreParams params = (RestoreParams)msg.obj;
Dan Egnor156411d2009-06-26 13:20:02 -0700394 (new PerformRestoreThread(params.transport, params.observer, params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700395 break;
396 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400397 }
398 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400399 }
400
Christopher Tate181fafa2009-05-14 11:12:14 -0700401 // Add the backup agents in the given package to our set of known backup participants.
402 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700403 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700404 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700405 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700406 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700407 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700408 }
409
Christopher Tate181fafa2009-05-14 11:12:14 -0700410 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700411 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700412 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700413 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
414 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700415 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
416 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700417 }
418 }
419
Dan Egnorefe52642009-06-24 00:16:33 -0700420 for (PackageInfo pkg : targetPkgs) {
421 if (packageName == null || pkg.packageName.equals(packageName)) {
422 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700423 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700424 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700425 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700426 mBackupParticipants.put(uid, set);
427 }
Dan Egnorefe52642009-06-24 00:16:33 -0700428 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700429 }
Christopher Tate487529a2009-04-29 14:03:25 -0700430 }
431 }
432
Christopher Tate6785dd82009-06-18 15:58:25 -0700433 // Remove the given package's entry from our known active set. If
434 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700435 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700436 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700437 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700438 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700439 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700440 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700441 int flags = PackageManager.GET_SIGNATURES;
442 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700443 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700444 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700445 }
446 } else {
447 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700448 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700449 }
450 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700451 }
452
Joe Onorato8ad02812009-05-13 01:41:44 -0400453 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700454 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700455 if (DEBUG) {
456 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
457 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700458 for (PackageInfo p : agents) {
459 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700460 }
461 }
Dan Egnorefe52642009-06-24 00:16:33 -0700462 for (PackageInfo pkg : agents) {
463 if (packageName == null || pkg.packageName.equals(packageName)) {
464 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700465 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700466 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700467 // Find the existing entry with the same package name, and remove it.
468 // We can't just remove(app) because the instances are different.
469 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700470 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700471 set.remove(entry);
472 break;
473 }
474 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700475 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700476 mBackupParticipants.delete(uid);
477 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700478 }
479 }
480 }
481 }
482
Christopher Tate181fafa2009-05-14 11:12:14 -0700483 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700484 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700485 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700486 int flags = PackageManager.GET_SIGNATURES;
487 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
488 int N = packages.size();
489 for (int a = N-1; a >= 0; a--) {
490 ApplicationInfo app = packages.get(a).applicationInfo;
491 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
492 || app.backupAgentName == null) {
493 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700494 }
495 }
Dan Egnorefe52642009-06-24 00:16:33 -0700496 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700497 }
Christopher Tateaa088442009-06-16 18:25:46 -0700498
Christopher Tate3799bc22009-05-06 16:13:56 -0700499 // Reset the given package's known backup participants. Unlike add/remove, the update
500 // action cannot be passed a null package name.
501 void updatePackageParticipantsLocked(String packageName) {
502 if (packageName == null) {
503 Log.e(TAG, "updatePackageParticipants called with null package name");
504 return;
505 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700506 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700507
508 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700509 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700510 removePackageParticipantsLockedInner(packageName, allApps);
511 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700512 }
513
Christopher Tate6785dd82009-06-18 15:58:25 -0700514 // The queue lock should be held when scheduling a backup pass
515 private void scheduleBackupPassLocked(long timeFromNowMillis) {
Christopher Tate6ef58a12009-06-29 14:56:28 -0700516 // We only schedule backups when we're actually enabled
517 synchronized (this) {
518 if (mEnabled) {
519 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
520 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
521 } else if (DEBUG) {
522 Log.v(TAG, "Disabled, so not scheduling backup pass");
523 }
524 }
Christopher Tate6785dd82009-06-18 15:58:25 -0700525 }
526
Dan Egnor87a02bc2009-06-17 02:30:10 -0700527 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700528 private IBackupTransport getTransport(String transportName) {
529 synchronized (mTransports) {
530 IBackupTransport transport = mTransports.get(transportName);
531 if (transport == null) {
532 Log.w(TAG, "Requested unavailable transport: " + transportName);
533 }
534 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700535 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700536 }
537
Christopher Tatedf01dea2009-06-09 20:45:02 -0700538 // fire off a backup agent, blocking until it attaches or times out
539 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
540 IBackupAgent agent = null;
541 synchronized(mAgentConnectLock) {
542 mConnecting = true;
543 mConnectedAgent = null;
544 try {
545 if (mActivityManager.bindBackupAgent(app, mode)) {
546 Log.d(TAG, "awaiting agent for " + app);
547
548 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700549 // only wait 10 seconds for the clear data to happen
550 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
551 while (mConnecting && mConnectedAgent == null
552 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700553 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700554 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700555 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700556 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700557 return null;
558 }
559 }
560
561 // if we timed out with no connect, abort and move on
562 if (mConnecting == true) {
563 Log.w(TAG, "Timeout waiting for agent " + app);
564 return null;
565 }
566 agent = mConnectedAgent;
567 }
568 } catch (RemoteException e) {
569 // can't happen
570 }
571 }
572 return agent;
573 }
574
Christopher Tatec7b31e32009-06-10 15:49:30 -0700575 // clear an application's data, blocking until the operation completes or times out
576 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700577 // Don't wipe packages marked allowClearUserData=false
578 try {
579 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
580 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
581 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
582 + packageName);
583 return;
584 }
585 } catch (NameNotFoundException e) {
586 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
587 return;
588 }
589
Christopher Tatec7b31e32009-06-10 15:49:30 -0700590 ClearDataObserver observer = new ClearDataObserver();
591
592 synchronized(mClearDataLock) {
593 mClearingData = true;
594 mPackageManager.clearApplicationUserData(packageName, observer);
595
596 // only wait 10 seconds for the clear data to happen
597 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
598 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
599 try {
600 mClearDataLock.wait(5000);
601 } catch (InterruptedException e) {
602 // won't happen, but still.
603 mClearingData = false;
604 }
605 }
606 }
607 }
608
609 class ClearDataObserver extends IPackageDataObserver.Stub {
610 public void onRemoveCompleted(String packageName, boolean succeeded)
611 throws android.os.RemoteException {
612 synchronized(mClearDataLock) {
613 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700614 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700615 }
616 }
617 }
618
Christopher Tate043dadc2009-06-02 16:11:00 -0700619 // ----- Back up a set of applications via a worker thread -----
620
621 class PerformBackupThread extends Thread {
622 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700623 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700624 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700625 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700626 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700627
Christopher Tateaa088442009-06-16 18:25:46 -0700628 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700629 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700630 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700631 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700632 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700633
634 try {
635 mStateDir = new File(mBaseStateDir, transport.transportDirName());
636 } catch (RemoteException e) {
637 // can't happen; the transport is local
638 }
639 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700640 }
641
642 @Override
643 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700644 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
645
Christopher Tate79588342009-06-30 16:11:49 -0700646 // Backups run at background priority
647 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
648
Christopher Tate5cb400b2009-06-25 16:03:14 -0700649 // The package manager doesn't have a proper <application> etc, but since
650 // it's running here in the system process we can just set up its agent
651 // directly and use a synthetic BackupRequest. We always run this pass
652 // because it's cheap and this way we guarantee that we don't get out of
653 // step even if we're selecting among various transports at run time.
654 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
655 mPackageManager, allAgentPackages());
656 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
657 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
658 processOneBackup(pmRequest,
659 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
660 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700661
662 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700663 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700664
665 // Finally, tear down the transport
666 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700667 if (!mTransport.finishBackup()) {
668 // STOPSHIP TODO: handle errors
669 Log.e(TAG, "Backup failure in finishBackup()");
670 }
671 } catch (RemoteException e) {
672 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700673 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700674
675 if (!mJournal.delete()) {
676 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
677 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700678 }
679
680 private void doQueuedBackups(IBackupTransport transport) {
681 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700682 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700683
684 IBackupAgent agent = null;
685 int mode = (request.fullBackup)
686 ? IApplicationThread.BACKUP_MODE_FULL
687 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
688 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700689 agent = bindToAgentSynchronous(request.appInfo, mode);
690 if (agent != null) {
691 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700692 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700693
694 // unbind even on timeout, just in case
695 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700696 } catch (SecurityException ex) {
697 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700698 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700699 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700700 Log.v(TAG, "bind/backup threw");
701 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700702 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700703
Christopher Tate043dadc2009-06-02 16:11:00 -0700704 }
705 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700706
707 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
708 final String packageName = request.appInfo.packageName;
709 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
710
711 try {
712 // Look up the package info & signatures. This is first so that if it
713 // throws an exception, there's no file setup yet that would need to
714 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700715 PackageInfo packInfo;
716 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
717 // The metadata 'package' is synthetic
718 packInfo = new PackageInfo();
719 packInfo.packageName = packageName;
720 } else {
721 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700722 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700723 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700724
725 // !!! TODO: get the state file dir from the transport
726 File savedStateName = new File(mStateDir, packageName);
727 File backupDataName = new File(mDataDir, packageName + ".data");
728 File newStateName = new File(mStateDir, packageName + ".new");
729
730 // In a full backup, we pass a null ParcelFileDescriptor as
731 // the saved-state "file"
732 ParcelFileDescriptor savedState = (request.fullBackup) ? null
733 : ParcelFileDescriptor.open(savedStateName,
734 ParcelFileDescriptor.MODE_READ_ONLY |
735 ParcelFileDescriptor.MODE_CREATE);
736
737 backupDataName.delete();
738 ParcelFileDescriptor backupData =
739 ParcelFileDescriptor.open(backupDataName,
740 ParcelFileDescriptor.MODE_READ_WRITE |
741 ParcelFileDescriptor.MODE_CREATE);
742
743 newStateName.delete();
744 ParcelFileDescriptor newState =
745 ParcelFileDescriptor.open(newStateName,
746 ParcelFileDescriptor.MODE_READ_WRITE |
747 ParcelFileDescriptor.MODE_CREATE);
748
749 // Run the target's backup pass
750 boolean success = false;
751 try {
752 agent.doBackup(savedState, backupData, newState);
753 success = true;
754 } finally {
755 if (savedState != null) {
756 savedState.close();
757 }
758 backupData.close();
759 newState.close();
760 }
761
762 // Now propagate the newly-backed-up data to the transport
763 if (success) {
764 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
765 backupData =
766 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700767 if (!transport.performBackup(packInfo, backupData)) {
768 // STOPSHIP TODO: handle errors
769 Log.e(TAG, "Backup failure in performBackup()");
770 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700771
772 // !!! TODO: After successful transport, delete the now-stale data
773 // and juggle the files so that next time the new state is passed
774 //backupDataName.delete();
775 newStateName.renameTo(savedStateName);
776 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700777 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700778 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700779 }
780 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700781 }
782
Christopher Tatedf01dea2009-06-09 20:45:02 -0700783
784 // ----- Restore handling -----
785
Christopher Tateabce4e82009-06-18 18:35:32 -0700786 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700787 // Allow unsigned apps, but not signed on one device and unsigned on the other
788 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700789 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
790 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700791 if ((storedSigs == null || storedSigs.length == 0)
792 && (deviceSigs == null || deviceSigs.length == 0)) {
793 return true;
794 }
795 if (storedSigs == null || deviceSigs == null) {
796 return false;
797 }
798
Christopher Tateabce4e82009-06-18 18:35:32 -0700799 // !!! TODO: this demands that every stored signature match one
800 // that is present on device, and does not demand the converse.
801 // Is this this right policy?
802 int nStored = storedSigs.length;
803 int nDevice = deviceSigs.length;
804
805 for (int i=0; i < nStored; i++) {
806 boolean match = false;
807 for (int j=0; j < nDevice; j++) {
808 if (storedSigs[i].equals(deviceSigs[j])) {
809 match = true;
810 break;
811 }
812 }
813 if (!match) {
814 return false;
815 }
816 }
817 return true;
818 }
819
Christopher Tatedf01dea2009-06-09 20:45:02 -0700820 class PerformRestoreThread extends Thread {
821 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700822 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700823 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700824 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700825 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700826
Christopher Tate5cbbf562009-06-22 16:44:51 -0700827 class RestoreRequest {
828 public PackageInfo app;
829 public int storedAppVersion;
830
831 RestoreRequest(PackageInfo _app, int _version) {
832 app = _app;
833 storedAppVersion = _version;
834 }
835 }
836
Christopher Tate7d562ec2009-06-25 18:03:43 -0700837 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700838 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700839 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700840 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700841 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700842
843 try {
844 mStateDir = new File(mBaseStateDir, transport.transportDirName());
845 } catch (RemoteException e) {
846 // can't happen; the transport is local
847 }
848 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700849 }
850
851 @Override
852 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700853 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700854 /**
855 * Restore sequence:
856 *
Dan Egnorefe52642009-06-24 00:16:33 -0700857 * 1. get the restore set description for our identity
858 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700859 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700860 * 3. for each app in the restore queue:
861 * 3.a. clear the app data
862 * 3.b. get the restore data for the app from the transport
863 * 3.c. launch the backup agent for the app
864 * 3.d. agent.doRestore() with the data from the server
865 * 3.e. unbind the agent [and kill the app?]
866 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700867 */
868
Christopher Tate7d562ec2009-06-25 18:03:43 -0700869 int error = -1; // assume error
870
Dan Egnorefe52642009-06-24 00:16:33 -0700871 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700872 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700873 RestoreSet[] images = mTransport.getAvailableRestoreSets();
874 if (images == null) {
875 // STOPSHIP TODO: Handle the failure somehow?
876 Log.e(TAG, "Error getting restore sets");
877 return;
878 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700879
Dan Egnorefe52642009-06-24 00:16:33 -0700880 if (images.length == 0) {
881 Log.i(TAG, "No restore sets available");
882 return;
883 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700884
Dan Egnorefe52642009-06-24 00:16:33 -0700885 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700886
Dan Egnorefe52642009-06-24 00:16:33 -0700887 // Get the list of all packages which have backup enabled.
888 // (Include the Package Manager metadata pseudo-package first.)
889 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
890 PackageInfo omPackage = new PackageInfo();
891 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
892 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700893
Dan Egnorefe52642009-06-24 00:16:33 -0700894 List<PackageInfo> agentPackages = allAgentPackages();
895 restorePackages.addAll(agentPackages);
896
Christopher Tate7d562ec2009-06-25 18:03:43 -0700897 // let the observer know that we're running
898 if (mObserver != null) {
899 try {
900 // !!! TODO: get an actual count from the transport after
901 // its startRestore() runs?
902 mObserver.restoreStarting(restorePackages.size());
903 } catch (RemoteException e) {
904 Log.d(TAG, "Restore observer died at restoreStarting");
905 mObserver = null;
906 }
907 }
908
Dan Egnor156411d2009-06-26 13:20:02 -0700909 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700910 // STOPSHIP TODO: Handle the failure somehow?
911 Log.e(TAG, "Error starting restore operation");
912 return;
913 }
914
915 String packageName = mTransport.nextRestorePackage();
916 if (packageName == null) {
917 // STOPSHIP TODO: Handle the failure somehow?
918 Log.e(TAG, "Error getting first restore package");
919 return;
920 } else if (packageName.equals("")) {
921 Log.i(TAG, "No restore data available");
922 return;
923 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
924 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
925 + "\", found only \"" + packageName + "\"");
926 return;
927 }
928
929 // Pull the Package Manager metadata from the restore set first
930 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
931 mPackageManager, agentPackages);
932 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
933
Christopher Tate7d562ec2009-06-25 18:03:43 -0700934 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700935 for (;;) {
936 packageName = mTransport.nextRestorePackage();
937 if (packageName == null) {
938 // STOPSHIP TODO: Handle the failure somehow?
939 Log.e(TAG, "Error getting next restore package");
940 return;
941 } else if (packageName.equals("")) {
942 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700943 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700944
Christopher Tate7d562ec2009-06-25 18:03:43 -0700945 if (mObserver != null) {
946 ++count;
947 try {
948 mObserver.onUpdate(count);
949 } catch (RemoteException e) {
950 Log.d(TAG, "Restore observer died in onUpdate");
951 mObserver = null;
952 }
953 }
954
Dan Egnorefe52642009-06-24 00:16:33 -0700955 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
956 if (metaInfo == null) {
957 Log.e(TAG, "Missing metadata for " + packageName);
958 continue;
959 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700960
Dan Egnorefe52642009-06-24 00:16:33 -0700961 int flags = PackageManager.GET_SIGNATURES;
962 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
963 if (metaInfo.versionCode > packageInfo.versionCode) {
964 Log.w(TAG, "Package " + packageName
965 + " restore version [" + metaInfo.versionCode
966 + "] is too new for installed version ["
967 + packageInfo.versionCode + "]");
968 continue;
969 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700970
Dan Egnorefe52642009-06-24 00:16:33 -0700971 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
972 Log.w(TAG, "Signature mismatch restoring " + packageName);
973 continue;
974 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700975
Dan Egnorefe52642009-06-24 00:16:33 -0700976 if (DEBUG) Log.v(TAG, "Package " + packageName
977 + " restore version [" + metaInfo.versionCode
978 + "] is compatible with installed version ["
979 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700980
Dan Egnorefe52642009-06-24 00:16:33 -0700981 // Now perform the actual restore
982 clearApplicationDataSynchronous(packageName);
983 IBackupAgent agent = bindToAgentSynchronous(
984 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700985 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700986 if (agent == null) {
987 Log.w(TAG, "Can't find backup agent for " + packageName);
988 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700989 }
990
Dan Egnorefe52642009-06-24 00:16:33 -0700991 try {
992 processOneRestore(packageInfo, metaInfo.versionCode, agent);
993 } finally {
994 // unbind even on timeout or failure, just in case
995 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
996 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700997 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700998
999 // if we get this far, report success to the observer
1000 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001001 } catch (NameNotFoundException e) {
1002 // STOPSHIP TODO: Handle the failure somehow?
1003 Log.e(TAG, "Invalid paackage restoring data", e);
1004 } catch (RemoteException e) {
1005 // STOPSHIP TODO: Handle the failure somehow?
1006 Log.e(TAG, "Error restoring data", e);
1007 } finally {
1008 try {
1009 mTransport.finishRestore();
1010 } catch (RemoteException e) {
1011 Log.e(TAG, "Error finishing restore", e);
1012 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001013
1014 if (mObserver != null) {
1015 try {
1016 mObserver.restoreFinished(error);
1017 } catch (RemoteException e) {
1018 Log.d(TAG, "Restore observer died at restoreFinished");
1019 }
1020 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001021 }
1022 }
1023
Dan Egnorefe52642009-06-24 00:16:33 -07001024 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1025 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001026 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001027 final String packageName = app.packageName;
1028
1029 // !!! TODO: get the dirs from the transport
1030 File backupDataName = new File(mDataDir, packageName + ".restore");
1031 backupDataName.delete();
1032 try {
1033 ParcelFileDescriptor backupData =
1034 ParcelFileDescriptor.open(backupDataName,
1035 ParcelFileDescriptor.MODE_READ_WRITE |
1036 ParcelFileDescriptor.MODE_CREATE);
1037
1038 // Run the transport's restore pass
1039 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001040 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001041 if (!mTransport.getRestoreData(backupData)) {
1042 // STOPSHIP TODO: Handle this error somehow?
1043 Log.e(TAG, "Error getting restore data for " + packageName);
1044 return;
1045 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001046 } finally {
1047 backupData.close();
1048 }
1049
1050 // Okay, we have the data. Now have the agent do the restore.
1051 File newStateName = new File(mStateDir, packageName + ".new");
1052 ParcelFileDescriptor newState =
1053 ParcelFileDescriptor.open(newStateName,
1054 ParcelFileDescriptor.MODE_READ_WRITE |
1055 ParcelFileDescriptor.MODE_CREATE);
1056
1057 backupData = ParcelFileDescriptor.open(backupDataName,
1058 ParcelFileDescriptor.MODE_READ_ONLY);
1059
Christopher Tatec7b31e32009-06-10 15:49:30 -07001060 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001061 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001062 } finally {
1063 newState.close();
1064 backupData.close();
1065 }
1066
1067 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001068 File savedStateName = new File(mStateDir, packageName);
1069 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001070 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001071 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001072 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001073 }
1074 }
1075
1076
Christopher Tate487529a2009-04-29 14:03:25 -07001077 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001078
Christopher Tatea8bf8152009-04-30 11:36:21 -07001079 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001080 // Record that we need a backup pass for the caller. Since multiple callers
1081 // may share a uid, we need to note all candidates within that uid and schedule
1082 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001083
1084 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001085
1086 // If the caller does not hold the BACKUP permission, it can only request a
1087 // backup of its own data.
1088 HashSet<ApplicationInfo> targets;
1089 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1090 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1091 targets = mBackupParticipants.get(Binder.getCallingUid());
1092 } else {
1093 // a caller with full permission can ask to back up any participating app
1094 // !!! TODO: allow backup of ANY app?
1095 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1096 targets = new HashSet<ApplicationInfo>();
1097 int N = mBackupParticipants.size();
1098 for (int i = 0; i < N; i++) {
1099 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1100 if (s != null) {
1101 targets.addAll(s);
1102 }
1103 }
1104 }
Christopher Tate487529a2009-04-29 14:03:25 -07001105 if (targets != null) {
1106 synchronized (mQueueLock) {
1107 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001108 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001109 // validate the caller-supplied package name against the known set of
1110 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001111 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001112 // Add the caller to the set of pending backups. If there is
1113 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001114 BackupRequest req = new BackupRequest(app, false);
1115 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001116
1117 // Journal this request in case of crash
1118 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001119 }
1120 }
1121
Christopher Tate181fafa2009-05-14 11:12:14 -07001122 if (DEBUG) {
1123 int numKeys = mPendingBackups.size();
Christopher Tate6ef58a12009-06-29 14:56:28 -07001124 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate181fafa2009-05-14 11:12:14 -07001125 for (BackupRequest b : mPendingBackups.values()) {
1126 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1127 }
1128 }
Christopher Tate487529a2009-04-29 14:03:25 -07001129 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001130 } else {
1131 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001132 }
1133 }
Christopher Tate46758122009-05-06 11:22:00 -07001134
Christopher Tatecde87f42009-06-12 12:55:53 -07001135 private void writeToJournalLocked(String str) {
1136 if (mJournalStream != null) {
1137 try {
1138 mJournalStream.writeUTF(str);
1139 } catch (IOException e) {
1140 Log.e(TAG, "Error writing to backup journal");
1141 mJournalStream = null;
1142 mJournal = null;
1143 }
1144 }
1145 }
1146
Christopher Tateace7f092009-06-15 18:07:25 -07001147 // Run a backup pass immediately for any applications that have declared
1148 // that they have pending updates.
1149 public void backupNow() throws RemoteException {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001150 mContext.enforceCallingPermission("android.permission.BACKUP", "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001151
Christopher Tateace7f092009-06-15 18:07:25 -07001152 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001153 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001154 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001155 }
1156 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001157
Christopher Tate6ef58a12009-06-29 14:56:28 -07001158 // Enable/disable the backup transport
1159 public void setBackupEnabled(boolean enable) {
1160 mContext.enforceCallingPermission("android.permission.BACKUP", "setBackupEnabled");
1161
1162 boolean wasEnabled = mEnabled;
1163 synchronized (this) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001164 Settings.Secure.putInt(mContext.getContentResolver(), BACKUP_ENABLED_SETTING,
1165 enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001166 mEnabled = enable;
1167 }
1168
Christopher Tate49401dd2009-07-01 12:34:29 -07001169 synchronized (mQueueLock) {
1170 if (enable && !wasEnabled) {
1171 // if we've just been enabled, start scheduling backup passes
1172 scheduleBackupPassLocked(BACKUP_INTERVAL);
1173 } else if (!enable) {
1174 // No longer enabled, so stop running backups.
1175 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001176 }
1177 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001178 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001179
1180 // Report whether the backup mechanism is currently enabled
1181 public boolean isBackupEnabled() {
1182 mContext.enforceCallingPermission("android.permission.BACKUP", "isBackupEnabled");
1183 return mEnabled; // no need to synchronize just to read it
1184 }
1185
Christopher Tate91717492009-06-26 21:07:13 -07001186 // Report the name of the currently active transport
1187 public String getCurrentTransport() {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001188 mContext.enforceCallingPermission("android.permission.BACKUP", "getCurrentTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001189 Log.v(TAG, "getCurrentTransport() returning " + mCurrentTransport);
1190 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001191 }
1192
Christopher Tate91717492009-06-26 21:07:13 -07001193 // Report all known, available backup transports
1194 public String[] listAllTransports() {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001195 mContext.enforceCallingPermission("android.permission.BACKUP", "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001196
Christopher Tate91717492009-06-26 21:07:13 -07001197 String[] list = null;
1198 ArrayList<String> known = new ArrayList<String>();
1199 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1200 if (entry.getValue() != null) {
1201 known.add(entry.getKey());
1202 }
1203 }
1204
1205 if (known.size() > 0) {
1206 list = new String[known.size()];
1207 known.toArray(list);
1208 }
1209 return list;
1210 }
1211
1212 // Select which transport to use for the next backup operation. If the given
1213 // name is not one of the available transports, no action is taken and the method
1214 // returns null.
1215 public String selectBackupTransport(String transport) {
1216 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1217
1218 synchronized (mTransports) {
1219 String prevTransport = null;
1220 if (mTransports.get(transport) != null) {
1221 prevTransport = mCurrentTransport;
1222 mCurrentTransport = transport;
Christopher Tatece0bf062009-07-01 11:43:53 -07001223 Settings.Secure.putString(mContext.getContentResolver(), BACKUP_TRANSPORT_SETTING,
1224 transport);
Christopher Tate91717492009-06-26 21:07:13 -07001225 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1226 + " returning " + prevTransport);
1227 } else {
1228 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1229 }
1230 return prevTransport;
1231 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001232 }
1233
1234 // Callback: a requested backup agent has been instantiated. This should only
1235 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001236 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001237 synchronized(mAgentConnectLock) {
1238 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1239 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1240 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1241 mConnectedAgent = agent;
1242 mConnecting = false;
1243 } else {
1244 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1245 + " claiming agent connected");
1246 }
1247 mAgentConnectLock.notifyAll();
1248 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001249 }
1250
1251 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1252 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001253 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001254 public void agentDisconnected(String packageName) {
1255 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001256 synchronized(mAgentConnectLock) {
1257 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1258 mConnectedAgent = null;
1259 mConnecting = false;
1260 } else {
1261 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1262 + " claiming agent disconnected");
1263 }
1264 mAgentConnectLock.notifyAll();
1265 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001266 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001267
Christopher Tate8c850b72009-06-07 19:33:20 -07001268 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001269 public IRestoreSession beginRestoreSession(String transport) {
Christopher Tate8c850b72009-06-07 19:33:20 -07001270 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001271
1272 synchronized(this) {
1273 if (mActiveRestoreSession != null) {
1274 Log.d(TAG, "Restore session requested but one already active");
1275 return null;
1276 }
Christopher Tate91717492009-06-26 21:07:13 -07001277 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001278 }
1279 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001280 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001281
Christopher Tate9b3905c2009-06-08 15:24:01 -07001282 // ----- Restore session -----
1283
1284 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001285 private static final String TAG = "RestoreSession";
1286
Christopher Tate9b3905c2009-06-08 15:24:01 -07001287 private IBackupTransport mRestoreTransport = null;
1288 RestoreSet[] mRestoreSets = null;
1289
Christopher Tate91717492009-06-26 21:07:13 -07001290 RestoreSession(String transport) {
1291 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001292 }
1293
1294 // --- Binder interface ---
1295 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001296 mContext.enforceCallingPermission("android.permission.BACKUP",
1297 "getAvailableRestoreSets");
1298
Christopher Tatef68eb502009-06-16 11:02:01 -07001299 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001300 synchronized(this) {
1301 if (mRestoreSets == null) {
1302 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1303 }
1304 return mRestoreSets;
1305 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001306 } catch (RuntimeException e) {
1307 Log.d(TAG, "getAvailableRestoreSets exception");
1308 e.printStackTrace();
1309 throw e;
1310 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001311 }
1312
Dan Egnor156411d2009-06-26 13:20:02 -07001313 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001314 throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001315 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1316
1317 if (mRestoreSets != null) {
1318 for (int i = 0; i < mRestoreSets.length; i++) {
1319 if (token == mRestoreSets[i].token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001320 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001321 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001322 mBackupHandler.sendMessage(msg);
1323 return 0;
1324 }
1325 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001326 } else {
1327 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001328 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001329 return -1;
1330 }
1331
1332 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001333 mContext.enforceCallingPermission("android.permission.BACKUP",
1334 "endRestoreSession");
1335
Dan Egnorefe52642009-06-24 00:16:33 -07001336 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001337 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001338 synchronized(BackupManagerService.this) {
1339 if (BackupManagerService.this.mActiveRestoreSession == this) {
1340 BackupManagerService.this.mActiveRestoreSession = null;
1341 } else {
1342 Log.e(TAG, "ending non-current restore session");
1343 }
1344 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001345 }
1346 }
1347
Christopher Tate043dadc2009-06-02 16:11:00 -07001348
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001349 @Override
1350 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1351 synchronized (mQueueLock) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001352 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled"));
Christopher Tate49401dd2009-07-01 12:34:29 -07001353 boolean scheduled = mBackupHandler.hasMessages(MSG_RUN_BACKUP);
1354 if (scheduled != mEnabled) {
1355 if (mEnabled) {
1356 pw.println("ERROR: backups enabled but none scheduled!");
1357 } else {
1358 pw.println("ERROR: backups are scheduled but not enabled!");
1359 }
1360 }
Christopher Tate91717492009-06-26 21:07:13 -07001361 pw.println("Available transports:");
1362 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001363 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1364 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001365 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001366 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001367 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001368 for (int i=0; i<N; i++) {
1369 int uid = mBackupParticipants.keyAt(i);
1370 pw.print(" uid: ");
1371 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001372 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1373 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001374 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001375 }
1376 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001377 pw.println("Pending: " + mPendingBackups.size());
1378 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001379 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001380 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001381 }
1382 }
Christopher Tate487529a2009-04-29 14:03:25 -07001383}