blob: b547f239b7a9c4f9c826530f0081ac8d9834a9df [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;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400394 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Dan Egnor156411d2009-06-26 13:20:02 -0700395 (new PerformRestoreThread(params.transport, params.observer, params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700396 break;
397 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400398 }
399 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400400 }
401
Christopher Tate181fafa2009-05-14 11:12:14 -0700402 // Add the backup agents in the given package to our set of known backup participants.
403 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700404 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700405 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700406 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700407 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700408 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700409 }
410
Christopher Tate181fafa2009-05-14 11:12:14 -0700411 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700412 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700413 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700414 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
415 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700416 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
417 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700418 }
419 }
420
Dan Egnorefe52642009-06-24 00:16:33 -0700421 for (PackageInfo pkg : targetPkgs) {
422 if (packageName == null || pkg.packageName.equals(packageName)) {
423 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700424 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700425 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700426 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700427 mBackupParticipants.put(uid, set);
428 }
Dan Egnorefe52642009-06-24 00:16:33 -0700429 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700430 }
Christopher Tate487529a2009-04-29 14:03:25 -0700431 }
432 }
433
Christopher Tate6785dd82009-06-18 15:58:25 -0700434 // Remove the given package's entry from our known active set. If
435 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700436 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700437 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700438 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700439 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700440 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700441 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700442 int flags = PackageManager.GET_SIGNATURES;
443 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700444 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700445 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700446 }
447 } else {
448 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700449 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700450 }
451 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700452 }
453
Joe Onorato8ad02812009-05-13 01:41:44 -0400454 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700455 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700456 if (DEBUG) {
457 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
458 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700459 for (PackageInfo p : agents) {
460 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700461 }
462 }
Dan Egnorefe52642009-06-24 00:16:33 -0700463 for (PackageInfo pkg : agents) {
464 if (packageName == null || pkg.packageName.equals(packageName)) {
465 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700466 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700467 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700468 // Find the existing entry with the same package name, and remove it.
469 // We can't just remove(app) because the instances are different.
470 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700471 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700472 set.remove(entry);
473 break;
474 }
475 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700476 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700477 mBackupParticipants.delete(uid);
478 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700479 }
480 }
481 }
482 }
483
Christopher Tate181fafa2009-05-14 11:12:14 -0700484 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700485 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700486 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700487 int flags = PackageManager.GET_SIGNATURES;
488 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
489 int N = packages.size();
490 for (int a = N-1; a >= 0; a--) {
491 ApplicationInfo app = packages.get(a).applicationInfo;
492 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
493 || app.backupAgentName == null) {
494 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700495 }
496 }
Dan Egnorefe52642009-06-24 00:16:33 -0700497 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700498 }
Christopher Tateaa088442009-06-16 18:25:46 -0700499
Christopher Tate3799bc22009-05-06 16:13:56 -0700500 // Reset the given package's known backup participants. Unlike add/remove, the update
501 // action cannot be passed a null package name.
502 void updatePackageParticipantsLocked(String packageName) {
503 if (packageName == null) {
504 Log.e(TAG, "updatePackageParticipants called with null package name");
505 return;
506 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700507 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700508
509 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700510 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700511 removePackageParticipantsLockedInner(packageName, allApps);
512 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700513 }
514
Christopher Tate6785dd82009-06-18 15:58:25 -0700515 // The queue lock should be held when scheduling a backup pass
516 private void scheduleBackupPassLocked(long timeFromNowMillis) {
Christopher Tate6ef58a12009-06-29 14:56:28 -0700517 // We only schedule backups when we're actually enabled
518 synchronized (this) {
519 if (mEnabled) {
520 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
521 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
522 } else if (DEBUG) {
523 Log.v(TAG, "Disabled, so not scheduling backup pass");
524 }
525 }
Christopher Tate6785dd82009-06-18 15:58:25 -0700526 }
527
Dan Egnor87a02bc2009-06-17 02:30:10 -0700528 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700529 private IBackupTransport getTransport(String transportName) {
530 synchronized (mTransports) {
531 IBackupTransport transport = mTransports.get(transportName);
532 if (transport == null) {
533 Log.w(TAG, "Requested unavailable transport: " + transportName);
534 }
535 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700536 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700537 }
538
Christopher Tatedf01dea2009-06-09 20:45:02 -0700539 // fire off a backup agent, blocking until it attaches or times out
540 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
541 IBackupAgent agent = null;
542 synchronized(mAgentConnectLock) {
543 mConnecting = true;
544 mConnectedAgent = null;
545 try {
546 if (mActivityManager.bindBackupAgent(app, mode)) {
547 Log.d(TAG, "awaiting agent for " + app);
548
549 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700550 // only wait 10 seconds for the clear data to happen
551 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
552 while (mConnecting && mConnectedAgent == null
553 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700554 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700555 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700556 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700557 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700558 return null;
559 }
560 }
561
562 // if we timed out with no connect, abort and move on
563 if (mConnecting == true) {
564 Log.w(TAG, "Timeout waiting for agent " + app);
565 return null;
566 }
567 agent = mConnectedAgent;
568 }
569 } catch (RemoteException e) {
570 // can't happen
571 }
572 }
573 return agent;
574 }
575
Christopher Tatec7b31e32009-06-10 15:49:30 -0700576 // clear an application's data, blocking until the operation completes or times out
577 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700578 // Don't wipe packages marked allowClearUserData=false
579 try {
580 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
581 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
582 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
583 + packageName);
584 return;
585 }
586 } catch (NameNotFoundException e) {
587 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
588 return;
589 }
590
Christopher Tatec7b31e32009-06-10 15:49:30 -0700591 ClearDataObserver observer = new ClearDataObserver();
592
593 synchronized(mClearDataLock) {
594 mClearingData = true;
595 mPackageManager.clearApplicationUserData(packageName, observer);
596
597 // only wait 10 seconds for the clear data to happen
598 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
599 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
600 try {
601 mClearDataLock.wait(5000);
602 } catch (InterruptedException e) {
603 // won't happen, but still.
604 mClearingData = false;
605 }
606 }
607 }
608 }
609
610 class ClearDataObserver extends IPackageDataObserver.Stub {
611 public void onRemoveCompleted(String packageName, boolean succeeded)
612 throws android.os.RemoteException {
613 synchronized(mClearDataLock) {
614 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700615 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700616 }
617 }
618 }
619
Christopher Tate043dadc2009-06-02 16:11:00 -0700620 // ----- Back up a set of applications via a worker thread -----
621
622 class PerformBackupThread extends Thread {
623 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700624 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700625 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700626 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700627 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700628
Christopher Tateaa088442009-06-16 18:25:46 -0700629 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700630 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700631 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700632 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700633 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700634
635 try {
636 mStateDir = new File(mBaseStateDir, transport.transportDirName());
637 } catch (RemoteException e) {
638 // can't happen; the transport is local
639 }
640 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700641 }
642
643 @Override
644 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700645 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
646
Christopher Tate79588342009-06-30 16:11:49 -0700647 // Backups run at background priority
648 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
649
Christopher Tate5cb400b2009-06-25 16:03:14 -0700650 // The package manager doesn't have a proper <application> etc, but since
651 // it's running here in the system process we can just set up its agent
652 // directly and use a synthetic BackupRequest. We always run this pass
653 // because it's cheap and this way we guarantee that we don't get out of
654 // step even if we're selecting among various transports at run time.
655 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
656 mPackageManager, allAgentPackages());
657 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
658 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
659 processOneBackup(pmRequest,
660 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
661 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700662
663 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700664 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700665
666 // Finally, tear down the transport
667 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700668 if (!mTransport.finishBackup()) {
669 // STOPSHIP TODO: handle errors
670 Log.e(TAG, "Backup failure in finishBackup()");
671 }
672 } catch (RemoteException e) {
673 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700674 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700675
676 if (!mJournal.delete()) {
677 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
678 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700679 }
680
681 private void doQueuedBackups(IBackupTransport transport) {
682 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700683 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700684
685 IBackupAgent agent = null;
686 int mode = (request.fullBackup)
687 ? IApplicationThread.BACKUP_MODE_FULL
688 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
689 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700690 agent = bindToAgentSynchronous(request.appInfo, mode);
691 if (agent != null) {
692 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700693 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700694
695 // unbind even on timeout, just in case
696 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700697 } catch (SecurityException ex) {
698 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700699 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700700 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700701 Log.v(TAG, "bind/backup threw");
702 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700703 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700704
Christopher Tate043dadc2009-06-02 16:11:00 -0700705 }
706 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700707
708 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
709 final String packageName = request.appInfo.packageName;
710 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
711
712 try {
713 // Look up the package info & signatures. This is first so that if it
714 // throws an exception, there's no file setup yet that would need to
715 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700716 PackageInfo packInfo;
717 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
718 // The metadata 'package' is synthetic
719 packInfo = new PackageInfo();
720 packInfo.packageName = packageName;
721 } else {
722 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700723 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700724 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700725
726 // !!! TODO: get the state file dir from the transport
727 File savedStateName = new File(mStateDir, packageName);
728 File backupDataName = new File(mDataDir, packageName + ".data");
729 File newStateName = new File(mStateDir, packageName + ".new");
730
731 // In a full backup, we pass a null ParcelFileDescriptor as
732 // the saved-state "file"
733 ParcelFileDescriptor savedState = (request.fullBackup) ? null
734 : ParcelFileDescriptor.open(savedStateName,
735 ParcelFileDescriptor.MODE_READ_ONLY |
736 ParcelFileDescriptor.MODE_CREATE);
737
738 backupDataName.delete();
739 ParcelFileDescriptor backupData =
740 ParcelFileDescriptor.open(backupDataName,
741 ParcelFileDescriptor.MODE_READ_WRITE |
742 ParcelFileDescriptor.MODE_CREATE);
743
744 newStateName.delete();
745 ParcelFileDescriptor newState =
746 ParcelFileDescriptor.open(newStateName,
747 ParcelFileDescriptor.MODE_READ_WRITE |
748 ParcelFileDescriptor.MODE_CREATE);
749
750 // Run the target's backup pass
751 boolean success = false;
752 try {
753 agent.doBackup(savedState, backupData, newState);
754 success = true;
755 } finally {
756 if (savedState != null) {
757 savedState.close();
758 }
759 backupData.close();
760 newState.close();
761 }
762
763 // Now propagate the newly-backed-up data to the transport
764 if (success) {
765 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
766 backupData =
767 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700768 if (!transport.performBackup(packInfo, backupData)) {
769 // STOPSHIP TODO: handle errors
770 Log.e(TAG, "Backup failure in performBackup()");
771 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700772
773 // !!! TODO: After successful transport, delete the now-stale data
774 // and juggle the files so that next time the new state is passed
775 //backupDataName.delete();
776 newStateName.renameTo(savedStateName);
777 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700778 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700779 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700780 }
781 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700782 }
783
Christopher Tatedf01dea2009-06-09 20:45:02 -0700784
785 // ----- Restore handling -----
786
Christopher Tateabce4e82009-06-18 18:35:32 -0700787 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700788 // Allow unsigned apps, but not signed on one device and unsigned on the other
789 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700790 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
791 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700792 if ((storedSigs == null || storedSigs.length == 0)
793 && (deviceSigs == null || deviceSigs.length == 0)) {
794 return true;
795 }
796 if (storedSigs == null || deviceSigs == null) {
797 return false;
798 }
799
Christopher Tateabce4e82009-06-18 18:35:32 -0700800 // !!! TODO: this demands that every stored signature match one
801 // that is present on device, and does not demand the converse.
802 // Is this this right policy?
803 int nStored = storedSigs.length;
804 int nDevice = deviceSigs.length;
805
806 for (int i=0; i < nStored; i++) {
807 boolean match = false;
808 for (int j=0; j < nDevice; j++) {
809 if (storedSigs[i].equals(deviceSigs[j])) {
810 match = true;
811 break;
812 }
813 }
814 if (!match) {
815 return false;
816 }
817 }
818 return true;
819 }
820
Christopher Tatedf01dea2009-06-09 20:45:02 -0700821 class PerformRestoreThread extends Thread {
822 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700823 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700824 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700825 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700826 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700827
Christopher Tate5cbbf562009-06-22 16:44:51 -0700828 class RestoreRequest {
829 public PackageInfo app;
830 public int storedAppVersion;
831
832 RestoreRequest(PackageInfo _app, int _version) {
833 app = _app;
834 storedAppVersion = _version;
835 }
836 }
837
Christopher Tate7d562ec2009-06-25 18:03:43 -0700838 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700839 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700840 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400841 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -0700842 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700843 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700844
845 try {
846 mStateDir = new File(mBaseStateDir, transport.transportDirName());
847 } catch (RemoteException e) {
848 // can't happen; the transport is local
849 }
850 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700851 }
852
853 @Override
854 public void run() {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400855 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
856 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700857 /**
858 * Restore sequence:
859 *
Dan Egnorefe52642009-06-24 00:16:33 -0700860 * 1. get the restore set description for our identity
861 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700862 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700863 * 3. for each app in the restore queue:
864 * 3.a. clear the app data
865 * 3.b. get the restore data for the app from the transport
866 * 3.c. launch the backup agent for the app
867 * 3.d. agent.doRestore() with the data from the server
868 * 3.e. unbind the agent [and kill the app?]
869 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700870 */
871
Christopher Tate7d562ec2009-06-25 18:03:43 -0700872 int error = -1; // assume error
873
Dan Egnorefe52642009-06-24 00:16:33 -0700874 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700875 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700876 RestoreSet[] images = mTransport.getAvailableRestoreSets();
877 if (images == null) {
878 // STOPSHIP TODO: Handle the failure somehow?
879 Log.e(TAG, "Error getting restore sets");
880 return;
881 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700882
Dan Egnorefe52642009-06-24 00:16:33 -0700883 if (images.length == 0) {
884 Log.i(TAG, "No restore sets available");
885 return;
886 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700887
Dan Egnorefe52642009-06-24 00:16:33 -0700888 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700889
Dan Egnorefe52642009-06-24 00:16:33 -0700890 // Get the list of all packages which have backup enabled.
891 // (Include the Package Manager metadata pseudo-package first.)
892 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
893 PackageInfo omPackage = new PackageInfo();
894 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
895 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700896
Dan Egnorefe52642009-06-24 00:16:33 -0700897 List<PackageInfo> agentPackages = allAgentPackages();
898 restorePackages.addAll(agentPackages);
899
Christopher Tate7d562ec2009-06-25 18:03:43 -0700900 // let the observer know that we're running
901 if (mObserver != null) {
902 try {
903 // !!! TODO: get an actual count from the transport after
904 // its startRestore() runs?
905 mObserver.restoreStarting(restorePackages.size());
906 } catch (RemoteException e) {
907 Log.d(TAG, "Restore observer died at restoreStarting");
908 mObserver = null;
909 }
910 }
911
Dan Egnor156411d2009-06-26 13:20:02 -0700912 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700913 // STOPSHIP TODO: Handle the failure somehow?
914 Log.e(TAG, "Error starting restore operation");
915 return;
916 }
917
918 String packageName = mTransport.nextRestorePackage();
919 if (packageName == null) {
920 // STOPSHIP TODO: Handle the failure somehow?
921 Log.e(TAG, "Error getting first restore package");
922 return;
923 } else if (packageName.equals("")) {
924 Log.i(TAG, "No restore data available");
925 return;
926 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
927 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
928 + "\", found only \"" + packageName + "\"");
929 return;
930 }
931
932 // Pull the Package Manager metadata from the restore set first
933 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
934 mPackageManager, agentPackages);
935 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
936
Christopher Tate7d562ec2009-06-25 18:03:43 -0700937 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700938 for (;;) {
939 packageName = mTransport.nextRestorePackage();
940 if (packageName == null) {
941 // STOPSHIP TODO: Handle the failure somehow?
942 Log.e(TAG, "Error getting next restore package");
943 return;
944 } else if (packageName.equals("")) {
945 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700946 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700947
Christopher Tate7d562ec2009-06-25 18:03:43 -0700948 if (mObserver != null) {
949 ++count;
950 try {
951 mObserver.onUpdate(count);
952 } catch (RemoteException e) {
953 Log.d(TAG, "Restore observer died in onUpdate");
954 mObserver = null;
955 }
956 }
957
Dan Egnorefe52642009-06-24 00:16:33 -0700958 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
959 if (metaInfo == null) {
960 Log.e(TAG, "Missing metadata for " + packageName);
961 continue;
962 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700963
Dan Egnorefe52642009-06-24 00:16:33 -0700964 int flags = PackageManager.GET_SIGNATURES;
965 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
966 if (metaInfo.versionCode > packageInfo.versionCode) {
967 Log.w(TAG, "Package " + packageName
968 + " restore version [" + metaInfo.versionCode
969 + "] is too new for installed version ["
970 + packageInfo.versionCode + "]");
971 continue;
972 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700973
Dan Egnorefe52642009-06-24 00:16:33 -0700974 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
975 Log.w(TAG, "Signature mismatch restoring " + packageName);
976 continue;
977 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700978
Dan Egnorefe52642009-06-24 00:16:33 -0700979 if (DEBUG) Log.v(TAG, "Package " + packageName
980 + " restore version [" + metaInfo.versionCode
981 + "] is compatible with installed version ["
982 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700983
Dan Egnorefe52642009-06-24 00:16:33 -0700984 // Now perform the actual restore
985 clearApplicationDataSynchronous(packageName);
986 IBackupAgent agent = bindToAgentSynchronous(
987 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700988 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700989 if (agent == null) {
990 Log.w(TAG, "Can't find backup agent for " + packageName);
991 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700992 }
993
Dan Egnorefe52642009-06-24 00:16:33 -0700994 try {
995 processOneRestore(packageInfo, metaInfo.versionCode, agent);
996 } finally {
997 // unbind even on timeout or failure, just in case
998 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
999 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001000 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001001
1002 // if we get this far, report success to the observer
1003 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001004 } catch (NameNotFoundException e) {
1005 // STOPSHIP TODO: Handle the failure somehow?
1006 Log.e(TAG, "Invalid paackage restoring data", e);
1007 } catch (RemoteException e) {
1008 // STOPSHIP TODO: Handle the failure somehow?
1009 Log.e(TAG, "Error restoring data", e);
1010 } finally {
1011 try {
1012 mTransport.finishRestore();
1013 } catch (RemoteException e) {
1014 Log.e(TAG, "Error finishing restore", e);
1015 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001016
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001017 Log.d(TAG, "finishing restore mObserver=" + mObserver);
1018
Christopher Tate7d562ec2009-06-25 18:03:43 -07001019 if (mObserver != null) {
1020 try {
1021 mObserver.restoreFinished(error);
1022 } catch (RemoteException e) {
1023 Log.d(TAG, "Restore observer died at restoreFinished");
1024 }
1025 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001026 }
1027 }
1028
Dan Egnorefe52642009-06-24 00:16:33 -07001029 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1030 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001031 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001032 final String packageName = app.packageName;
1033
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001034 Log.d(TAG, "processOneRestore packageName=" + packageName);
1035
Christopher Tatec7b31e32009-06-10 15:49:30 -07001036 // !!! TODO: get the dirs from the transport
1037 File backupDataName = new File(mDataDir, packageName + ".restore");
1038 backupDataName.delete();
1039 try {
1040 ParcelFileDescriptor backupData =
1041 ParcelFileDescriptor.open(backupDataName,
1042 ParcelFileDescriptor.MODE_READ_WRITE |
1043 ParcelFileDescriptor.MODE_CREATE);
1044
1045 // Run the transport's restore pass
1046 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001047 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001048 if (!mTransport.getRestoreData(backupData)) {
1049 // STOPSHIP TODO: Handle this error somehow?
1050 Log.e(TAG, "Error getting restore data for " + packageName);
1051 return;
1052 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001053 } finally {
1054 backupData.close();
1055 }
1056
1057 // Okay, we have the data. Now have the agent do the restore.
1058 File newStateName = new File(mStateDir, packageName + ".new");
1059 ParcelFileDescriptor newState =
1060 ParcelFileDescriptor.open(newStateName,
1061 ParcelFileDescriptor.MODE_READ_WRITE |
1062 ParcelFileDescriptor.MODE_CREATE);
1063
1064 backupData = ParcelFileDescriptor.open(backupDataName,
1065 ParcelFileDescriptor.MODE_READ_ONLY);
1066
Christopher Tatec7b31e32009-06-10 15:49:30 -07001067 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001068 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001069 } finally {
1070 newState.close();
1071 backupData.close();
1072 }
1073
1074 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001075 File savedStateName = new File(mStateDir, packageName);
1076 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001077 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001078 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001079 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001080 }
1081 }
1082
1083
Christopher Tate487529a2009-04-29 14:03:25 -07001084 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001085
Christopher Tatea8bf8152009-04-30 11:36:21 -07001086 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001087 // Record that we need a backup pass for the caller. Since multiple callers
1088 // may share a uid, we need to note all candidates within that uid and schedule
1089 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001090
1091 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001092
1093 // If the caller does not hold the BACKUP permission, it can only request a
1094 // backup of its own data.
1095 HashSet<ApplicationInfo> targets;
1096 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1097 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1098 targets = mBackupParticipants.get(Binder.getCallingUid());
1099 } else {
1100 // a caller with full permission can ask to back up any participating app
1101 // !!! TODO: allow backup of ANY app?
1102 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1103 targets = new HashSet<ApplicationInfo>();
1104 int N = mBackupParticipants.size();
1105 for (int i = 0; i < N; i++) {
1106 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1107 if (s != null) {
1108 targets.addAll(s);
1109 }
1110 }
1111 }
Christopher Tate487529a2009-04-29 14:03:25 -07001112 if (targets != null) {
1113 synchronized (mQueueLock) {
1114 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001115 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001116 // validate the caller-supplied package name against the known set of
1117 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001118 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001119 // Add the caller to the set of pending backups. If there is
1120 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001121 BackupRequest req = new BackupRequest(app, false);
1122 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001123
1124 // Journal this request in case of crash
1125 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001126 }
1127 }
1128
Christopher Tate181fafa2009-05-14 11:12:14 -07001129 if (DEBUG) {
1130 int numKeys = mPendingBackups.size();
Christopher Tate6ef58a12009-06-29 14:56:28 -07001131 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate181fafa2009-05-14 11:12:14 -07001132 for (BackupRequest b : mPendingBackups.values()) {
1133 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1134 }
1135 }
Christopher Tate487529a2009-04-29 14:03:25 -07001136 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001137 } else {
1138 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001139 }
1140 }
Christopher Tate46758122009-05-06 11:22:00 -07001141
Christopher Tatecde87f42009-06-12 12:55:53 -07001142 private void writeToJournalLocked(String str) {
1143 if (mJournalStream != null) {
1144 try {
1145 mJournalStream.writeUTF(str);
1146 } catch (IOException e) {
1147 Log.e(TAG, "Error writing to backup journal");
1148 mJournalStream = null;
1149 mJournal = null;
1150 }
1151 }
1152 }
1153
Christopher Tateace7f092009-06-15 18:07:25 -07001154 // Run a backup pass immediately for any applications that have declared
1155 // that they have pending updates.
1156 public void backupNow() throws RemoteException {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001157 mContext.enforceCallingPermission("android.permission.BACKUP", "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001158
Christopher Tateace7f092009-06-15 18:07:25 -07001159 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001160 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001161 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001162 }
1163 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001164
Christopher Tate6ef58a12009-06-29 14:56:28 -07001165 // Enable/disable the backup transport
1166 public void setBackupEnabled(boolean enable) {
1167 mContext.enforceCallingPermission("android.permission.BACKUP", "setBackupEnabled");
1168
1169 boolean wasEnabled = mEnabled;
1170 synchronized (this) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001171 Settings.Secure.putInt(mContext.getContentResolver(), BACKUP_ENABLED_SETTING,
1172 enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001173 mEnabled = enable;
1174 }
1175
Christopher Tate49401dd2009-07-01 12:34:29 -07001176 synchronized (mQueueLock) {
1177 if (enable && !wasEnabled) {
1178 // if we've just been enabled, start scheduling backup passes
1179 scheduleBackupPassLocked(BACKUP_INTERVAL);
1180 } else if (!enable) {
1181 // No longer enabled, so stop running backups.
1182 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001183 }
1184 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001185 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001186
1187 // Report whether the backup mechanism is currently enabled
1188 public boolean isBackupEnabled() {
1189 mContext.enforceCallingPermission("android.permission.BACKUP", "isBackupEnabled");
1190 return mEnabled; // no need to synchronize just to read it
1191 }
1192
Christopher Tate91717492009-06-26 21:07:13 -07001193 // Report the name of the currently active transport
1194 public String getCurrentTransport() {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001195 mContext.enforceCallingPermission("android.permission.BACKUP", "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001196 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001197 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001198 }
1199
Christopher Tate91717492009-06-26 21:07:13 -07001200 // Report all known, available backup transports
1201 public String[] listAllTransports() {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001202 mContext.enforceCallingPermission("android.permission.BACKUP", "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001203
Christopher Tate91717492009-06-26 21:07:13 -07001204 String[] list = null;
1205 ArrayList<String> known = new ArrayList<String>();
1206 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1207 if (entry.getValue() != null) {
1208 known.add(entry.getKey());
1209 }
1210 }
1211
1212 if (known.size() > 0) {
1213 list = new String[known.size()];
1214 known.toArray(list);
1215 }
1216 return list;
1217 }
1218
1219 // Select which transport to use for the next backup operation. If the given
1220 // name is not one of the available transports, no action is taken and the method
1221 // returns null.
1222 public String selectBackupTransport(String transport) {
1223 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1224
1225 synchronized (mTransports) {
1226 String prevTransport = null;
1227 if (mTransports.get(transport) != null) {
1228 prevTransport = mCurrentTransport;
1229 mCurrentTransport = transport;
Christopher Tatece0bf062009-07-01 11:43:53 -07001230 Settings.Secure.putString(mContext.getContentResolver(), BACKUP_TRANSPORT_SETTING,
1231 transport);
Christopher Tate91717492009-06-26 21:07:13 -07001232 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1233 + " returning " + prevTransport);
1234 } else {
1235 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1236 }
1237 return prevTransport;
1238 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001239 }
1240
1241 // Callback: a requested backup agent has been instantiated. This should only
1242 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001243 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001244 synchronized(mAgentConnectLock) {
1245 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1246 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1247 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1248 mConnectedAgent = agent;
1249 mConnecting = false;
1250 } else {
1251 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1252 + " claiming agent connected");
1253 }
1254 mAgentConnectLock.notifyAll();
1255 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001256 }
1257
1258 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1259 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001260 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001261 public void agentDisconnected(String packageName) {
1262 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001263 synchronized(mAgentConnectLock) {
1264 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1265 mConnectedAgent = null;
1266 mConnecting = false;
1267 } else {
1268 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1269 + " claiming agent disconnected");
1270 }
1271 mAgentConnectLock.notifyAll();
1272 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001273 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001274
Christopher Tate8c850b72009-06-07 19:33:20 -07001275 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001276 public IRestoreSession beginRestoreSession(String transport) {
Christopher Tate8c850b72009-06-07 19:33:20 -07001277 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001278
1279 synchronized(this) {
1280 if (mActiveRestoreSession != null) {
1281 Log.d(TAG, "Restore session requested but one already active");
1282 return null;
1283 }
Christopher Tate91717492009-06-26 21:07:13 -07001284 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001285 }
1286 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001287 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001288
Christopher Tate9b3905c2009-06-08 15:24:01 -07001289 // ----- Restore session -----
1290
1291 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001292 private static final String TAG = "RestoreSession";
1293
Christopher Tate9b3905c2009-06-08 15:24:01 -07001294 private IBackupTransport mRestoreTransport = null;
1295 RestoreSet[] mRestoreSets = null;
1296
Christopher Tate91717492009-06-26 21:07:13 -07001297 RestoreSession(String transport) {
1298 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001299 }
1300
1301 // --- Binder interface ---
1302 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001303 mContext.enforceCallingPermission("android.permission.BACKUP",
1304 "getAvailableRestoreSets");
1305
Christopher Tatef68eb502009-06-16 11:02:01 -07001306 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001307 synchronized(this) {
1308 if (mRestoreSets == null) {
1309 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1310 }
1311 return mRestoreSets;
1312 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001313 } catch (RuntimeException e) {
1314 Log.d(TAG, "getAvailableRestoreSets exception");
1315 e.printStackTrace();
1316 throw e;
1317 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001318 }
1319
Dan Egnor156411d2009-06-26 13:20:02 -07001320 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001321 throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001322 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1323
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001324 Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
1325
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001326 if (mRestoreSets != null) {
1327 for (int i = 0; i < mRestoreSets.length; i++) {
1328 if (token == mRestoreSets[i].token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001329 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001330 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001331 mBackupHandler.sendMessage(msg);
1332 return 0;
1333 }
1334 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001335 } else {
1336 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001337 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001338 return -1;
1339 }
1340
1341 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001342 mContext.enforceCallingPermission("android.permission.BACKUP",
1343 "endRestoreSession");
1344
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001345 Log.d(TAG, "endRestoreSession");
1346
Dan Egnorefe52642009-06-24 00:16:33 -07001347 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001348 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001349 synchronized(BackupManagerService.this) {
1350 if (BackupManagerService.this.mActiveRestoreSession == this) {
1351 BackupManagerService.this.mActiveRestoreSession = null;
1352 } else {
1353 Log.e(TAG, "ending non-current restore session");
1354 }
1355 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001356 }
1357 }
1358
Christopher Tate043dadc2009-06-02 16:11:00 -07001359
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001360 @Override
1361 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1362 synchronized (mQueueLock) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001363 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled"));
Christopher Tate49401dd2009-07-01 12:34:29 -07001364 boolean scheduled = mBackupHandler.hasMessages(MSG_RUN_BACKUP);
1365 if (scheduled != mEnabled) {
1366 if (mEnabled) {
1367 pw.println("ERROR: backups enabled but none scheduled!");
1368 } else {
1369 pw.println("ERROR: backups are scheduled but not enabled!");
1370 }
1371 }
Christopher Tate91717492009-06-26 21:07:13 -07001372 pw.println("Available transports:");
1373 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001374 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1375 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001376 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001377 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001378 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001379 for (int i=0; i<N; i++) {
1380 int uid = mBackupParticipants.keyAt(i);
1381 pw.print(" uid: ");
1382 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001383 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1384 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001385 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001386 }
1387 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001388 pw.println("Pending: " + mPendingBackups.size());
1389 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001390 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001391 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001392 }
1393 }
Christopher Tate487529a2009-04-29 14:03:25 -07001394}