blob: 953e4012ee76f10f6c0c30a9a45d6a251b0b5bab [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 Tate49401dd2009-07-01 12:34:29 -070077 // How often we perform a backup pass. Privileged external callers can
78 // trigger an immediate pass.
79 private static final long BACKUP_INTERVAL = 60 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070080
81 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070082 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070083 private static final int MSG_RUN_RESTORE = 3;
Christopher Tatec7b31e32009-06-10 15:49:30 -070084
85 // Timeout interval for deciding that a bind or clear-data has taken too long
86 static final long TIMEOUT_INTERVAL = 10 * 1000;
87
Christopher Tate487529a2009-04-29 14:03:25 -070088 private Context mContext;
89 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -070090 private IActivityManager mActivityManager;
91 private boolean mEnabled; // access to this is synchronized on 'this'
Christopher Tate487529a2009-04-29 14:03:25 -070092 private final BackupHandler mBackupHandler = new BackupHandler();
93 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate6ef58a12009-06-29 14:56:28 -070094 private final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -070095 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070096 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070097 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070098 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070099 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700100
Christopher Tate181fafa2009-05-14 11:12:14 -0700101 BackupRequest(ApplicationInfo app, boolean isFull) {
102 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700103 fullBackup = isFull;
104 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700105
106 public String toString() {
107 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
108 }
Christopher Tate46758122009-05-06 11:22:00 -0700109 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400110 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700111 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
112 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700113
114 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate6785dd82009-06-18 15:58:25 -0700115 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700116
117 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700118 private final Object mQueueLock = new Object();
119
Christopher Tate043dadc2009-06-02 16:11:00 -0700120 // The thread performing the sequence of queued backups binds to each app's agent
121 // in succession. Bind notifications are asynchronously delivered through the
122 // Activity Manager; use this lock object to signal when a requested binding has
123 // completed.
124 private final Object mAgentConnectLock = new Object();
125 private IBackupAgent mConnectedAgent;
126 private volatile boolean mConnecting;
127
Christopher Tatec7b31e32009-06-10 15:49:30 -0700128 // A similar synchronicity mechanism around clearing apps' data for restore
129 private final Object mClearDataLock = new Object();
130 private volatile boolean mClearingData;
131
Christopher Tate91717492009-06-26 21:07:13 -0700132 // Transport bookkeeping
Christopher Tate91717492009-06-26 21:07:13 -0700133 private final HashMap<String,IBackupTransport> mTransports
134 = new HashMap<String,IBackupTransport>();
135 private String mCurrentTransport;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700136 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700137 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700138
Christopher Tate7d562ec2009-06-25 18:03:43 -0700139 private class RestoreParams {
140 public IBackupTransport transport;
141 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700142 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700143
Dan Egnor156411d2009-06-26 13:20:02 -0700144 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700145 transport = _transport;
146 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700147 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700148 }
149 }
150
Christopher Tate5cb400b2009-06-25 16:03:14 -0700151 // Where we keep our journal files and other bookkeeping
152 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700153 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700154 private File mJournalDir;
155 private File mJournal;
156 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700157
Christopher Tate487529a2009-04-29 14:03:25 -0700158 public BackupManagerService(Context context) {
159 mContext = context;
160 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700161 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700162
Christopher Tate22b87872009-05-04 16:41:53 -0700163 // Set up our bookkeeping
Dianne Hackborncf098292009-07-01 19:55:20 -0700164 mEnabled = Settings.Secure.getInt(context.getContentResolver(),
165 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700166 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700167 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700168
Christopher Tatecde87f42009-06-12 12:55:53 -0700169 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700170 mJournalDir = new File(mBaseStateDir, "pending");
171 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700172 makeJournalLocked(); // okay because no other threads are running yet
173
Christopher Tateabce4e82009-06-18 18:35:32 -0700174 // Build our mapping of uid to backup client services. This implicitly
175 // schedules a backup pass on the Package Manager metadata the first
176 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700177 synchronized (mBackupParticipants) {
178 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700179 }
180
Dan Egnor87a02bc2009-06-17 02:30:10 -0700181 // Set up our transport options and initialize the default transport
182 // TODO: Have transports register themselves somehow?
183 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700184 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700185 ComponentName localName = new ComponentName(context, LocalTransport.class);
186 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700187
Christopher Tate91717492009-06-26 21:07:13 -0700188 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700189 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
190 Settings.Secure.BACKUP_TRANSPORT);
191 if ("".equals(mCurrentTransport)) {
192 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700193 }
Christopher Tate91717492009-06-26 21:07:13 -0700194 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
195
196 // Attach to the Google backup transport. When this comes up, it will set
197 // itself as the current transport because we explicitly reset mCurrentTransport
198 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700199 Intent intent = new Intent().setComponent(new ComponentName(
200 "com.google.android.backup",
201 "com.google.android.backup.BackupTransportService"));
202 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700203
Christopher Tatecde87f42009-06-12 12:55:53 -0700204 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700205 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700206 parseLeftoverJournals();
207
Christopher Tate3799bc22009-05-06 16:13:56 -0700208 // Register for broadcasts about package install, etc., so we can
209 // update the provider list.
210 IntentFilter filter = new IntentFilter();
211 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
212 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
213 filter.addDataScheme("package");
214 mContext.registerReceiver(mBroadcastReceiver, filter);
Christopher Tate49401dd2009-07-01 12:34:29 -0700215
216 // Schedule the first backup pass -- okay because no other threads are
217 // running yet
218 if (mEnabled) {
219 scheduleBackupPassLocked(BACKUP_INTERVAL);
220 }
221}
Christopher Tate3799bc22009-05-06 16:13:56 -0700222
Christopher Tatecde87f42009-06-12 12:55:53 -0700223 private void makeJournalLocked() {
224 try {
225 mJournal = File.createTempFile("journal", null, mJournalDir);
226 mJournalStream = new RandomAccessFile(mJournal, "rwd");
227 } catch (IOException e) {
228 Log.e(TAG, "Unable to write backup journals");
229 mJournal = null;
230 mJournalStream = null;
231 }
232 }
233
234 private void parseLeftoverJournals() {
235 if (mJournal != null) {
236 File[] allJournals = mJournalDir.listFiles();
237 for (File f : allJournals) {
238 if (f.compareTo(mJournal) != 0) {
239 // This isn't the current journal, so it must be a leftover. Read
240 // out the package names mentioned there and schedule them for
241 // backup.
242 try {
243 Log.i(TAG, "Found stale backup journal, scheduling:");
244 RandomAccessFile in = new RandomAccessFile(f, "r");
245 while (true) {
246 String packageName = in.readUTF();
247 Log.i(TAG, " + " + packageName);
248 dataChanged(packageName);
249 }
250 } catch (EOFException e) {
251 // no more data; we're done
252 } catch (Exception e) {
253 // can't read it or other error; just skip it
254 } finally {
255 // close/delete the file
256 f.delete();
257 }
258 }
259 }
260 }
261 }
262
Christopher Tate91717492009-06-26 21:07:13 -0700263 // Add a transport to our set of available backends
264 private void registerTransport(String name, IBackupTransport transport) {
265 synchronized (mTransports) {
266 mTransports.put(name, transport);
267 }
268 }
269
Christopher Tate3799bc22009-05-06 16:13:56 -0700270 // ----- Track installation/removal of packages -----
271 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
272 public void onReceive(Context context, Intent intent) {
273 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
274
275 Uri uri = intent.getData();
276 if (uri == null) {
277 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700278 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700279 String pkgName = uri.getSchemeSpecificPart();
280 if (pkgName == null) {
281 return;
282 }
283
284 String action = intent.getAction();
285 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
286 synchronized (mBackupParticipants) {
287 Bundle extras = intent.getExtras();
288 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
289 // The package was just upgraded
290 updatePackageParticipantsLocked(pkgName);
291 } else {
292 // The package was just added
293 addPackageParticipantsLocked(pkgName);
294 }
295 }
296 }
297 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
298 Bundle extras = intent.getExtras();
299 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
300 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
301 } else {
302 synchronized (mBackupParticipants) {
303 removePackageParticipantsLocked(pkgName);
304 }
305 }
306 }
307 }
308 };
309
Dan Egnor87a02bc2009-06-17 02:30:10 -0700310 // ----- Track connection to GoogleBackupTransport service -----
311 ServiceConnection mGoogleConnection = new ServiceConnection() {
312 public void onServiceConnected(ComponentName name, IBinder service) {
313 if (DEBUG) Log.v(TAG, "Connected to Google transport");
314 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700315 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700316 }
317
318 public void onServiceDisconnected(ComponentName name) {
319 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
320 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700321 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700322 }
323 };
324
Joe Onorato8ad02812009-05-13 01:41:44 -0400325 // ----- Run the actual backup process asynchronously -----
326
Christopher Tate181fafa2009-05-14 11:12:14 -0700327 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400328 public void handleMessage(Message msg) {
329
330 switch (msg.what) {
331 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700332 {
Christopher Tate91717492009-06-26 21:07:13 -0700333 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700334 if (transport == null) {
335 Log.v(TAG, "Backup requested but no transport available");
336 break;
337 }
338
Joe Onorato8ad02812009-05-13 01:41:44 -0400339 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700340 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700341 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400342 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700343 // Do we have any work to do?
344 if (mPendingBackups.size() > 0) {
345 for (BackupRequest b: mPendingBackups.values()) {
346 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700347 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700348 Log.v(TAG, "clearing pending backups");
349 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700350
Christopher Tate49401dd2009-07-01 12:34:29 -0700351 // Start a new backup-queue journal file too
352 if (mJournalStream != null) {
353 try {
354 mJournalStream.close();
355 } catch (IOException e) {
356 // don't need to do anything
357 }
358 makeJournalLocked();
359 }
360
361 // At this point, we have started a new journal file, and the old
362 // file identity is being passed to the backup processing thread.
363 // When it completes successfully, that old journal file will be
364 // deleted. If we crash prior to that, the old journal is parsed
365 // at next boot and the journaled requests fulfilled.
366 (new PerformBackupThread(transport, queue, oldJournal)).start();
367 } else {
368 Log.v(TAG, "Backup requested but nothing pending");
369 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400370 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700371
Christopher Tate49401dd2009-07-01 12:34:29 -0700372 // Schedule the next pass.
373 synchronized (mQueueLock) {
374 scheduleBackupPassLocked(BACKUP_INTERVAL);
375 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700376 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700377 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700378
379 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400380 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700381
382 case MSG_RUN_RESTORE:
383 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700384 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400385 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Dan Egnor156411d2009-06-26 13:20:02 -0700386 (new PerformRestoreThread(params.transport, params.observer, params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700387 break;
388 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400389 }
390 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400391 }
392
Christopher Tate181fafa2009-05-14 11:12:14 -0700393 // Add the backup agents in the given package to our set of known backup participants.
394 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700395 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700396 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700397 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700398 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700399 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700400 }
401
Christopher Tate181fafa2009-05-14 11:12:14 -0700402 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700403 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700404 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700405 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
406 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700407 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
408 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700409 }
410 }
411
Dan Egnorefe52642009-06-24 00:16:33 -0700412 for (PackageInfo pkg : targetPkgs) {
413 if (packageName == null || pkg.packageName.equals(packageName)) {
414 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700415 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700416 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700417 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700418 mBackupParticipants.put(uid, set);
419 }
Dan Egnorefe52642009-06-24 00:16:33 -0700420 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700421 }
Christopher Tate487529a2009-04-29 14:03:25 -0700422 }
423 }
424
Christopher Tate6785dd82009-06-18 15:58:25 -0700425 // Remove the given package's entry from our known active set. If
426 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700427 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700428 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700429 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700430 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700431 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700432 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700433 int flags = PackageManager.GET_SIGNATURES;
434 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700435 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700436 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700437 }
438 } else {
439 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700440 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700441 }
442 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700443 }
444
Joe Onorato8ad02812009-05-13 01:41:44 -0400445 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700446 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700447 if (DEBUG) {
448 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
449 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700450 for (PackageInfo p : agents) {
451 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700452 }
453 }
Dan Egnorefe52642009-06-24 00:16:33 -0700454 for (PackageInfo pkg : agents) {
455 if (packageName == null || pkg.packageName.equals(packageName)) {
456 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700457 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700458 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700459 // Find the existing entry with the same package name, and remove it.
460 // We can't just remove(app) because the instances are different.
461 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700462 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700463 set.remove(entry);
464 break;
465 }
466 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700467 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700468 mBackupParticipants.delete(uid);
469 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700470 }
471 }
472 }
473 }
474
Christopher Tate181fafa2009-05-14 11:12:14 -0700475 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700476 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700477 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700478 int flags = PackageManager.GET_SIGNATURES;
479 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
480 int N = packages.size();
481 for (int a = N-1; a >= 0; a--) {
482 ApplicationInfo app = packages.get(a).applicationInfo;
483 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
484 || app.backupAgentName == null) {
485 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700486 }
487 }
Dan Egnorefe52642009-06-24 00:16:33 -0700488 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700489 }
Christopher Tateaa088442009-06-16 18:25:46 -0700490
Christopher Tate3799bc22009-05-06 16:13:56 -0700491 // Reset the given package's known backup participants. Unlike add/remove, the update
492 // action cannot be passed a null package name.
493 void updatePackageParticipantsLocked(String packageName) {
494 if (packageName == null) {
495 Log.e(TAG, "updatePackageParticipants called with null package name");
496 return;
497 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700498 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700499
500 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700501 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700502 removePackageParticipantsLockedInner(packageName, allApps);
503 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700504 }
505
Christopher Tate6785dd82009-06-18 15:58:25 -0700506 // The queue lock should be held when scheduling a backup pass
507 private void scheduleBackupPassLocked(long timeFromNowMillis) {
Christopher Tate6ef58a12009-06-29 14:56:28 -0700508 // We only schedule backups when we're actually enabled
509 synchronized (this) {
510 if (mEnabled) {
511 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
512 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
513 } else if (DEBUG) {
514 Log.v(TAG, "Disabled, so not scheduling backup pass");
515 }
516 }
Christopher Tate6785dd82009-06-18 15:58:25 -0700517 }
518
Dan Egnor87a02bc2009-06-17 02:30:10 -0700519 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700520 private IBackupTransport getTransport(String transportName) {
521 synchronized (mTransports) {
522 IBackupTransport transport = mTransports.get(transportName);
523 if (transport == null) {
524 Log.w(TAG, "Requested unavailable transport: " + transportName);
525 }
526 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700527 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700528 }
529
Christopher Tatedf01dea2009-06-09 20:45:02 -0700530 // fire off a backup agent, blocking until it attaches or times out
531 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
532 IBackupAgent agent = null;
533 synchronized(mAgentConnectLock) {
534 mConnecting = true;
535 mConnectedAgent = null;
536 try {
537 if (mActivityManager.bindBackupAgent(app, mode)) {
538 Log.d(TAG, "awaiting agent for " + app);
539
540 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700541 // only wait 10 seconds for the clear data to happen
542 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
543 while (mConnecting && mConnectedAgent == null
544 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700545 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700546 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700547 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700548 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700549 return null;
550 }
551 }
552
553 // if we timed out with no connect, abort and move on
554 if (mConnecting == true) {
555 Log.w(TAG, "Timeout waiting for agent " + app);
556 return null;
557 }
558 agent = mConnectedAgent;
559 }
560 } catch (RemoteException e) {
561 // can't happen
562 }
563 }
564 return agent;
565 }
566
Christopher Tatec7b31e32009-06-10 15:49:30 -0700567 // clear an application's data, blocking until the operation completes or times out
568 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700569 // Don't wipe packages marked allowClearUserData=false
570 try {
571 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
572 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
573 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
574 + packageName);
575 return;
576 }
577 } catch (NameNotFoundException e) {
578 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
579 return;
580 }
581
Christopher Tatec7b31e32009-06-10 15:49:30 -0700582 ClearDataObserver observer = new ClearDataObserver();
583
584 synchronized(mClearDataLock) {
585 mClearingData = true;
586 mPackageManager.clearApplicationUserData(packageName, observer);
587
588 // only wait 10 seconds for the clear data to happen
589 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
590 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
591 try {
592 mClearDataLock.wait(5000);
593 } catch (InterruptedException e) {
594 // won't happen, but still.
595 mClearingData = false;
596 }
597 }
598 }
599 }
600
601 class ClearDataObserver extends IPackageDataObserver.Stub {
602 public void onRemoveCompleted(String packageName, boolean succeeded)
603 throws android.os.RemoteException {
604 synchronized(mClearDataLock) {
605 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700606 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700607 }
608 }
609 }
610
Christopher Tate043dadc2009-06-02 16:11:00 -0700611 // ----- Back up a set of applications via a worker thread -----
612
613 class PerformBackupThread extends Thread {
614 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700615 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700616 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700617 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700618 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700619
Christopher Tateaa088442009-06-16 18:25:46 -0700620 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700621 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700622 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700623 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700624 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700625
626 try {
627 mStateDir = new File(mBaseStateDir, transport.transportDirName());
628 } catch (RemoteException e) {
629 // can't happen; the transport is local
630 }
631 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700632 }
633
634 @Override
635 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700636 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
637
Christopher Tate79588342009-06-30 16:11:49 -0700638 // Backups run at background priority
639 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
640
Christopher Tate5cb400b2009-06-25 16:03:14 -0700641 // The package manager doesn't have a proper <application> etc, but since
642 // it's running here in the system process we can just set up its agent
643 // directly and use a synthetic BackupRequest. We always run this pass
644 // because it's cheap and this way we guarantee that we don't get out of
645 // step even if we're selecting among various transports at run time.
646 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
647 mPackageManager, allAgentPackages());
648 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
649 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
650 processOneBackup(pmRequest,
651 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
652 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700653
654 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700655 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700656
657 // Finally, tear down the transport
658 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700659 if (!mTransport.finishBackup()) {
660 // STOPSHIP TODO: handle errors
661 Log.e(TAG, "Backup failure in finishBackup()");
662 }
663 } catch (RemoteException e) {
664 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700665 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700666
667 if (!mJournal.delete()) {
668 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
669 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700670 }
671
672 private void doQueuedBackups(IBackupTransport transport) {
673 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700674 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700675
676 IBackupAgent agent = null;
677 int mode = (request.fullBackup)
678 ? IApplicationThread.BACKUP_MODE_FULL
679 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
680 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700681 agent = bindToAgentSynchronous(request.appInfo, mode);
682 if (agent != null) {
683 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700684 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700685
686 // unbind even on timeout, just in case
687 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700688 } catch (SecurityException ex) {
689 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700690 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700691 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700692 Log.v(TAG, "bind/backup threw");
693 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700694 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700695
Christopher Tate043dadc2009-06-02 16:11:00 -0700696 }
697 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700698
699 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
700 final String packageName = request.appInfo.packageName;
701 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
702
703 try {
704 // Look up the package info & signatures. This is first so that if it
705 // throws an exception, there's no file setup yet that would need to
706 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700707 PackageInfo packInfo;
708 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
709 // The metadata 'package' is synthetic
710 packInfo = new PackageInfo();
711 packInfo.packageName = packageName;
712 } else {
713 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700714 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700715 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700716
717 // !!! TODO: get the state file dir from the transport
718 File savedStateName = new File(mStateDir, packageName);
719 File backupDataName = new File(mDataDir, packageName + ".data");
720 File newStateName = new File(mStateDir, packageName + ".new");
721
722 // In a full backup, we pass a null ParcelFileDescriptor as
723 // the saved-state "file"
724 ParcelFileDescriptor savedState = (request.fullBackup) ? null
725 : ParcelFileDescriptor.open(savedStateName,
726 ParcelFileDescriptor.MODE_READ_ONLY |
727 ParcelFileDescriptor.MODE_CREATE);
728
729 backupDataName.delete();
730 ParcelFileDescriptor backupData =
731 ParcelFileDescriptor.open(backupDataName,
732 ParcelFileDescriptor.MODE_READ_WRITE |
733 ParcelFileDescriptor.MODE_CREATE);
734
735 newStateName.delete();
736 ParcelFileDescriptor newState =
737 ParcelFileDescriptor.open(newStateName,
738 ParcelFileDescriptor.MODE_READ_WRITE |
739 ParcelFileDescriptor.MODE_CREATE);
740
741 // Run the target's backup pass
742 boolean success = false;
743 try {
744 agent.doBackup(savedState, backupData, newState);
745 success = true;
746 } finally {
747 if (savedState != null) {
748 savedState.close();
749 }
750 backupData.close();
751 newState.close();
752 }
753
754 // Now propagate the newly-backed-up data to the transport
755 if (success) {
756 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
757 backupData =
758 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700759 if (!transport.performBackup(packInfo, backupData)) {
760 // STOPSHIP TODO: handle errors
761 Log.e(TAG, "Backup failure in performBackup()");
762 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700763
764 // !!! TODO: After successful transport, delete the now-stale data
765 // and juggle the files so that next time the new state is passed
766 //backupDataName.delete();
767 newStateName.renameTo(savedStateName);
768 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700769 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700770 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700771 }
772 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700773 }
774
Christopher Tatedf01dea2009-06-09 20:45:02 -0700775
776 // ----- Restore handling -----
777
Christopher Tateabce4e82009-06-18 18:35:32 -0700778 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700779 // Allow unsigned apps, but not signed on one device and unsigned on the other
780 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700781 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
782 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700783 if ((storedSigs == null || storedSigs.length == 0)
784 && (deviceSigs == null || deviceSigs.length == 0)) {
785 return true;
786 }
787 if (storedSigs == null || deviceSigs == null) {
788 return false;
789 }
790
Christopher Tateabce4e82009-06-18 18:35:32 -0700791 // !!! TODO: this demands that every stored signature match one
792 // that is present on device, and does not demand the converse.
793 // Is this this right policy?
794 int nStored = storedSigs.length;
795 int nDevice = deviceSigs.length;
796
797 for (int i=0; i < nStored; i++) {
798 boolean match = false;
799 for (int j=0; j < nDevice; j++) {
800 if (storedSigs[i].equals(deviceSigs[j])) {
801 match = true;
802 break;
803 }
804 }
805 if (!match) {
806 return false;
807 }
808 }
809 return true;
810 }
811
Christopher Tatedf01dea2009-06-09 20:45:02 -0700812 class PerformRestoreThread extends Thread {
813 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700814 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700815 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700816 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700817 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700818
Christopher Tate5cbbf562009-06-22 16:44:51 -0700819 class RestoreRequest {
820 public PackageInfo app;
821 public int storedAppVersion;
822
823 RestoreRequest(PackageInfo _app, int _version) {
824 app = _app;
825 storedAppVersion = _version;
826 }
827 }
828
Christopher Tate7d562ec2009-06-25 18:03:43 -0700829 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700830 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700831 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400832 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -0700833 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700834 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700835
836 try {
837 mStateDir = new File(mBaseStateDir, transport.transportDirName());
838 } catch (RemoteException e) {
839 // can't happen; the transport is local
840 }
841 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700842 }
843
844 @Override
845 public void run() {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400846 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
847 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700848 /**
849 * Restore sequence:
850 *
Dan Egnorefe52642009-06-24 00:16:33 -0700851 * 1. get the restore set description for our identity
852 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700853 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700854 * 3. for each app in the restore queue:
855 * 3.a. clear the app data
856 * 3.b. get the restore data for the app from the transport
857 * 3.c. launch the backup agent for the app
858 * 3.d. agent.doRestore() with the data from the server
859 * 3.e. unbind the agent [and kill the app?]
860 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700861 */
862
Christopher Tate7d562ec2009-06-25 18:03:43 -0700863 int error = -1; // assume error
864
Dan Egnorefe52642009-06-24 00:16:33 -0700865 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700866 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700867 RestoreSet[] images = mTransport.getAvailableRestoreSets();
868 if (images == null) {
869 // STOPSHIP TODO: Handle the failure somehow?
870 Log.e(TAG, "Error getting restore sets");
871 return;
872 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700873
Dan Egnorefe52642009-06-24 00:16:33 -0700874 if (images.length == 0) {
875 Log.i(TAG, "No restore sets available");
876 return;
877 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700878
Dan Egnorefe52642009-06-24 00:16:33 -0700879 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700880
Dan Egnorefe52642009-06-24 00:16:33 -0700881 // Get the list of all packages which have backup enabled.
882 // (Include the Package Manager metadata pseudo-package first.)
883 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
884 PackageInfo omPackage = new PackageInfo();
885 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
886 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700887
Dan Egnorefe52642009-06-24 00:16:33 -0700888 List<PackageInfo> agentPackages = allAgentPackages();
889 restorePackages.addAll(agentPackages);
890
Christopher Tate7d562ec2009-06-25 18:03:43 -0700891 // let the observer know that we're running
892 if (mObserver != null) {
893 try {
894 // !!! TODO: get an actual count from the transport after
895 // its startRestore() runs?
896 mObserver.restoreStarting(restorePackages.size());
897 } catch (RemoteException e) {
898 Log.d(TAG, "Restore observer died at restoreStarting");
899 mObserver = null;
900 }
901 }
902
Dan Egnor156411d2009-06-26 13:20:02 -0700903 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700904 // STOPSHIP TODO: Handle the failure somehow?
905 Log.e(TAG, "Error starting restore operation");
906 return;
907 }
908
909 String packageName = mTransport.nextRestorePackage();
910 if (packageName == null) {
911 // STOPSHIP TODO: Handle the failure somehow?
912 Log.e(TAG, "Error getting first restore package");
913 return;
914 } else if (packageName.equals("")) {
915 Log.i(TAG, "No restore data available");
916 return;
917 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
918 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
919 + "\", found only \"" + packageName + "\"");
920 return;
921 }
922
923 // Pull the Package Manager metadata from the restore set first
924 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
925 mPackageManager, agentPackages);
926 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
927
Christopher Tate7d562ec2009-06-25 18:03:43 -0700928 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700929 for (;;) {
930 packageName = mTransport.nextRestorePackage();
931 if (packageName == null) {
932 // STOPSHIP TODO: Handle the failure somehow?
933 Log.e(TAG, "Error getting next restore package");
934 return;
935 } else if (packageName.equals("")) {
936 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700937 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700938
Christopher Tate7d562ec2009-06-25 18:03:43 -0700939 if (mObserver != null) {
940 ++count;
941 try {
942 mObserver.onUpdate(count);
943 } catch (RemoteException e) {
944 Log.d(TAG, "Restore observer died in onUpdate");
945 mObserver = null;
946 }
947 }
948
Dan Egnorefe52642009-06-24 00:16:33 -0700949 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
950 if (metaInfo == null) {
951 Log.e(TAG, "Missing metadata for " + packageName);
952 continue;
953 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700954
Dan Egnorefe52642009-06-24 00:16:33 -0700955 int flags = PackageManager.GET_SIGNATURES;
956 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
957 if (metaInfo.versionCode > packageInfo.versionCode) {
958 Log.w(TAG, "Package " + packageName
959 + " restore version [" + metaInfo.versionCode
960 + "] is too new for installed version ["
961 + packageInfo.versionCode + "]");
962 continue;
963 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700964
Dan Egnorefe52642009-06-24 00:16:33 -0700965 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
966 Log.w(TAG, "Signature mismatch restoring " + packageName);
967 continue;
968 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700969
Dan Egnorefe52642009-06-24 00:16:33 -0700970 if (DEBUG) Log.v(TAG, "Package " + packageName
971 + " restore version [" + metaInfo.versionCode
972 + "] is compatible with installed version ["
973 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700974
Dan Egnorefe52642009-06-24 00:16:33 -0700975 // Now perform the actual restore
976 clearApplicationDataSynchronous(packageName);
977 IBackupAgent agent = bindToAgentSynchronous(
978 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700979 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700980 if (agent == null) {
981 Log.w(TAG, "Can't find backup agent for " + packageName);
982 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700983 }
984
Dan Egnorefe52642009-06-24 00:16:33 -0700985 try {
986 processOneRestore(packageInfo, metaInfo.versionCode, agent);
987 } finally {
988 // unbind even on timeout or failure, just in case
989 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
990 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700991 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700992
993 // if we get this far, report success to the observer
994 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700995 } catch (NameNotFoundException e) {
996 // STOPSHIP TODO: Handle the failure somehow?
997 Log.e(TAG, "Invalid paackage restoring data", e);
998 } catch (RemoteException e) {
999 // STOPSHIP TODO: Handle the failure somehow?
1000 Log.e(TAG, "Error restoring data", e);
1001 } finally {
1002 try {
1003 mTransport.finishRestore();
1004 } catch (RemoteException e) {
1005 Log.e(TAG, "Error finishing restore", e);
1006 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001007
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001008 Log.d(TAG, "finishing restore mObserver=" + mObserver);
1009
Christopher Tate7d562ec2009-06-25 18:03:43 -07001010 if (mObserver != null) {
1011 try {
1012 mObserver.restoreFinished(error);
1013 } catch (RemoteException e) {
1014 Log.d(TAG, "Restore observer died at restoreFinished");
1015 }
1016 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001017 }
1018 }
1019
Dan Egnorefe52642009-06-24 00:16:33 -07001020 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1021 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001022 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001023 final String packageName = app.packageName;
1024
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001025 Log.d(TAG, "processOneRestore packageName=" + packageName);
1026
Christopher Tatec7b31e32009-06-10 15:49:30 -07001027 // !!! TODO: get the dirs from the transport
1028 File backupDataName = new File(mDataDir, packageName + ".restore");
1029 backupDataName.delete();
1030 try {
1031 ParcelFileDescriptor backupData =
1032 ParcelFileDescriptor.open(backupDataName,
1033 ParcelFileDescriptor.MODE_READ_WRITE |
1034 ParcelFileDescriptor.MODE_CREATE);
1035
1036 // Run the transport's restore pass
1037 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001038 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001039 if (!mTransport.getRestoreData(backupData)) {
1040 // STOPSHIP TODO: Handle this error somehow?
1041 Log.e(TAG, "Error getting restore data for " + packageName);
1042 return;
1043 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001044 } finally {
1045 backupData.close();
1046 }
1047
1048 // Okay, we have the data. Now have the agent do the restore.
1049 File newStateName = new File(mStateDir, packageName + ".new");
1050 ParcelFileDescriptor newState =
1051 ParcelFileDescriptor.open(newStateName,
1052 ParcelFileDescriptor.MODE_READ_WRITE |
1053 ParcelFileDescriptor.MODE_CREATE);
1054
1055 backupData = ParcelFileDescriptor.open(backupDataName,
1056 ParcelFileDescriptor.MODE_READ_ONLY);
1057
Christopher Tatec7b31e32009-06-10 15:49:30 -07001058 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001059 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001060 } finally {
1061 newState.close();
1062 backupData.close();
1063 }
1064
1065 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001066 File savedStateName = new File(mStateDir, packageName);
1067 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001068 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001069 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001070 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001071 }
1072 }
1073
1074
Christopher Tate487529a2009-04-29 14:03:25 -07001075 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001076
Christopher Tatea8bf8152009-04-30 11:36:21 -07001077 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001078 // Record that we need a backup pass for the caller. Since multiple callers
1079 // may share a uid, we need to note all candidates within that uid and schedule
1080 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001081
1082 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001083
1084 // If the caller does not hold the BACKUP permission, it can only request a
1085 // backup of its own data.
1086 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001087 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001088 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1089 targets = mBackupParticipants.get(Binder.getCallingUid());
1090 } else {
1091 // a caller with full permission can ask to back up any participating app
1092 // !!! TODO: allow backup of ANY app?
1093 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1094 targets = new HashSet<ApplicationInfo>();
1095 int N = mBackupParticipants.size();
1096 for (int i = 0; i < N; i++) {
1097 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1098 if (s != null) {
1099 targets.addAll(s);
1100 }
1101 }
1102 }
Christopher Tate487529a2009-04-29 14:03:25 -07001103 if (targets != null) {
1104 synchronized (mQueueLock) {
1105 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001106 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001107 // validate the caller-supplied package name against the known set of
1108 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001109 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001110 // Add the caller to the set of pending backups. If there is
1111 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001112 BackupRequest req = new BackupRequest(app, false);
1113 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001114
1115 // Journal this request in case of crash
1116 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001117 }
1118 }
1119
Christopher Tate181fafa2009-05-14 11:12:14 -07001120 if (DEBUG) {
1121 int numKeys = mPendingBackups.size();
Christopher Tate6ef58a12009-06-29 14:56:28 -07001122 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate181fafa2009-05-14 11:12:14 -07001123 for (BackupRequest b : mPendingBackups.values()) {
1124 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1125 }
1126 }
Christopher Tate487529a2009-04-29 14:03:25 -07001127 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001128 } else {
1129 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001130 }
1131 }
Christopher Tate46758122009-05-06 11:22:00 -07001132
Christopher Tatecde87f42009-06-12 12:55:53 -07001133 private void writeToJournalLocked(String str) {
1134 if (mJournalStream != null) {
1135 try {
1136 mJournalStream.writeUTF(str);
1137 } catch (IOException e) {
1138 Log.e(TAG, "Error writing to backup journal");
1139 mJournalStream = null;
1140 mJournal = null;
1141 }
1142 }
1143 }
1144
Christopher Tateace7f092009-06-15 18:07:25 -07001145 // Run a backup pass immediately for any applications that have declared
1146 // that they have pending updates.
1147 public void backupNow() throws RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001148 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001149
Christopher Tateace7f092009-06-15 18:07:25 -07001150 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001151 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001152 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001153 }
1154 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001155
Christopher Tate6ef58a12009-06-29 14:56:28 -07001156 // Enable/disable the backup transport
1157 public void setBackupEnabled(boolean enable) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001158 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001159
1160 boolean wasEnabled = mEnabled;
1161 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001162 Settings.Secure.putInt(mContext.getContentResolver(),
1163 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001164 mEnabled = enable;
1165 }
1166
Christopher Tate49401dd2009-07-01 12:34:29 -07001167 synchronized (mQueueLock) {
1168 if (enable && !wasEnabled) {
1169 // if we've just been enabled, start scheduling backup passes
1170 scheduleBackupPassLocked(BACKUP_INTERVAL);
1171 } else if (!enable) {
1172 // No longer enabled, so stop running backups.
1173 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001174 }
1175 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001176 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001177
1178 // Report whether the backup mechanism is currently enabled
1179 public boolean isBackupEnabled() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001180 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001181 return mEnabled; // no need to synchronize just to read it
1182 }
1183
Christopher Tate91717492009-06-26 21:07:13 -07001184 // Report the name of the currently active transport
1185 public String getCurrentTransport() {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001186 mContext.enforceCallingPermission("android.permission.BACKUP", "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001187 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001188 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001189 }
1190
Christopher Tate91717492009-06-26 21:07:13 -07001191 // Report all known, available backup transports
1192 public String[] listAllTransports() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001193 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001194
Christopher Tate91717492009-06-26 21:07:13 -07001195 String[] list = null;
1196 ArrayList<String> known = new ArrayList<String>();
1197 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1198 if (entry.getValue() != null) {
1199 known.add(entry.getKey());
1200 }
1201 }
1202
1203 if (known.size() > 0) {
1204 list = new String[known.size()];
1205 known.toArray(list);
1206 }
1207 return list;
1208 }
1209
1210 // Select which transport to use for the next backup operation. If the given
1211 // name is not one of the available transports, no action is taken and the method
1212 // returns null.
1213 public String selectBackupTransport(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001214 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001215
1216 synchronized (mTransports) {
1217 String prevTransport = null;
1218 if (mTransports.get(transport) != null) {
1219 prevTransport = mCurrentTransport;
1220 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001221 Settings.Secure.putString(mContext.getContentResolver(),
1222 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001223 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1224 + " returning " + prevTransport);
1225 } else {
1226 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1227 }
1228 return prevTransport;
1229 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001230 }
1231
1232 // Callback: a requested backup agent has been instantiated. This should only
1233 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001234 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001235 synchronized(mAgentConnectLock) {
1236 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1237 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1238 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1239 mConnectedAgent = agent;
1240 mConnecting = false;
1241 } else {
1242 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1243 + " claiming agent connected");
1244 }
1245 mAgentConnectLock.notifyAll();
1246 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001247 }
1248
1249 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1250 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001251 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001252 public void agentDisconnected(String packageName) {
1253 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001254 synchronized(mAgentConnectLock) {
1255 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1256 mConnectedAgent = null;
1257 mConnecting = false;
1258 } else {
1259 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1260 + " claiming agent disconnected");
1261 }
1262 mAgentConnectLock.notifyAll();
1263 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001264 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001265
Christopher Tate8c850b72009-06-07 19:33:20 -07001266 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001267 public IRestoreSession beginRestoreSession(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001268 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001269
1270 synchronized(this) {
1271 if (mActiveRestoreSession != null) {
1272 Log.d(TAG, "Restore session requested but one already active");
1273 return null;
1274 }
Christopher Tate91717492009-06-26 21:07:13 -07001275 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001276 }
1277 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001278 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001279
Christopher Tate9b3905c2009-06-08 15:24:01 -07001280 // ----- Restore session -----
1281
1282 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001283 private static final String TAG = "RestoreSession";
1284
Christopher Tate9b3905c2009-06-08 15:24:01 -07001285 private IBackupTransport mRestoreTransport = null;
1286 RestoreSet[] mRestoreSets = null;
1287
Christopher Tate91717492009-06-26 21:07:13 -07001288 RestoreSession(String transport) {
1289 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001290 }
1291
1292 // --- Binder interface ---
1293 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001294 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001295 "getAvailableRestoreSets");
1296
Christopher Tatef68eb502009-06-16 11:02:01 -07001297 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001298 synchronized(this) {
1299 if (mRestoreSets == null) {
1300 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1301 }
1302 return mRestoreSets;
1303 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001304 } catch (RuntimeException e) {
1305 Log.d(TAG, "getAvailableRestoreSets exception");
1306 e.printStackTrace();
1307 throw e;
1308 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001309 }
1310
Dan Egnor156411d2009-06-26 13:20:02 -07001311 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001312 throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001313 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001314
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001315 Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
1316
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001317 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 {
Dianne Hackborncf098292009-07-01 19:55:20 -07001333 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001334 "endRestoreSession");
1335
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001336 Log.d(TAG, "endRestoreSession");
1337
Dan Egnorefe52642009-06-24 00:16:33 -07001338 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001339 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001340 synchronized(BackupManagerService.this) {
1341 if (BackupManagerService.this.mActiveRestoreSession == this) {
1342 BackupManagerService.this.mActiveRestoreSession = null;
1343 } else {
1344 Log.e(TAG, "ending non-current restore session");
1345 }
1346 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001347 }
1348 }
1349
Christopher Tate043dadc2009-06-02 16:11:00 -07001350
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001351 @Override
1352 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1353 synchronized (mQueueLock) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001354 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled"));
Christopher Tate49401dd2009-07-01 12:34:29 -07001355 boolean scheduled = mBackupHandler.hasMessages(MSG_RUN_BACKUP);
1356 if (scheduled != mEnabled) {
1357 if (mEnabled) {
1358 pw.println("ERROR: backups enabled but none scheduled!");
1359 } else {
1360 pw.println("ERROR: backups are scheduled but not enabled!");
1361 }
1362 }
Christopher Tate91717492009-06-26 21:07:13 -07001363 pw.println("Available transports:");
1364 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001365 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1366 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001367 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001368 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001369 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001370 for (int i=0; i<N; i++) {
1371 int uid = mBackupParticipants.keyAt(i);
1372 pw.print(" uid: ");
1373 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001374 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1375 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001376 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001377 }
1378 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001379 pw.println("Pending: " + mPendingBackups.size());
1380 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001381 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001382 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001383 }
1384 }
Christopher Tate487529a2009-04-29 14:03:25 -07001385}