blob: 08300ffb2fe77dae21aa4a62c228e98791c85e19 [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 Tate6785dd82009-06-18 15:58:25 -070081 // Default time to wait after data changes before we back up the data
Christopher Tate111bd4a2009-06-24 17:29:38 -070082 private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070083
84 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070085 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070086 private static final int MSG_RUN_RESTORE = 3;
Christopher Tatec7b31e32009-06-10 15:49:30 -070087
88 // Timeout interval for deciding that a bind or clear-data has taken too long
89 static final long TIMEOUT_INTERVAL = 10 * 1000;
90
Christopher Tate487529a2009-04-29 14:03:25 -070091 private Context mContext;
92 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -070093 private IActivityManager mActivityManager;
94 private boolean mEnabled; // access to this is synchronized on 'this'
Christopher Tate487529a2009-04-29 14:03:25 -070095 private final BackupHandler mBackupHandler = new BackupHandler();
96 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate6ef58a12009-06-29 14:56:28 -070097 private final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -070098 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070099 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -0700100 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700101 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700102 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700103
Christopher Tate181fafa2009-05-14 11:12:14 -0700104 BackupRequest(ApplicationInfo app, boolean isFull) {
105 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700106 fullBackup = isFull;
107 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700108
109 public String toString() {
110 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
111 }
Christopher Tate46758122009-05-06 11:22:00 -0700112 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400113 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700114 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
115 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700116
117 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate6785dd82009-06-18 15:58:25 -0700118 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700119
120 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700121 private final Object mQueueLock = new Object();
122
Christopher Tate043dadc2009-06-02 16:11:00 -0700123 // The thread performing the sequence of queued backups binds to each app's agent
124 // in succession. Bind notifications are asynchronously delivered through the
125 // Activity Manager; use this lock object to signal when a requested binding has
126 // completed.
127 private final Object mAgentConnectLock = new Object();
128 private IBackupAgent mConnectedAgent;
129 private volatile boolean mConnecting;
130
Christopher Tatec7b31e32009-06-10 15:49:30 -0700131 // A similar synchronicity mechanism around clearing apps' data for restore
132 private final Object mClearDataLock = new Object();
133 private volatile boolean mClearingData;
134
Christopher Tate91717492009-06-26 21:07:13 -0700135 // Transport bookkeeping
Christopher Tate91717492009-06-26 21:07:13 -0700136 private final HashMap<String,IBackupTransport> mTransports
137 = new HashMap<String,IBackupTransport>();
138 private String mCurrentTransport;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700139 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700140 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700141
Christopher Tate7d562ec2009-06-25 18:03:43 -0700142 private class RestoreParams {
143 public IBackupTransport transport;
144 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700145 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700146
Dan Egnor156411d2009-06-26 13:20:02 -0700147 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700148 transport = _transport;
149 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700150 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700151 }
152 }
153
Christopher Tate5cb400b2009-06-25 16:03:14 -0700154 // Where we keep our journal files and other bookkeeping
155 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700156 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700157 private File mJournalDir;
158 private File mJournal;
159 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700160
Christopher Tate487529a2009-04-29 14:03:25 -0700161 public BackupManagerService(Context context) {
162 mContext = context;
163 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700164 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700165
Christopher Tate22b87872009-05-04 16:41:53 -0700166 // Set up our bookkeeping
Christopher Tate6ef58a12009-06-29 14:56:28 -0700167 // !!! STOPSHIP: make this disabled by default so that we then gate on
168 // setupwizard or other opt-out UI
Christopher Tatece0bf062009-07-01 11:43:53 -0700169 mEnabled = (Settings.Secure.getInt(mContext.getContentResolver(),
170 BACKUP_ENABLED_SETTING, 1) != 0);
Christopher Tate5cb400b2009-06-25 16:03:14 -0700171 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700172 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700173
Christopher Tatecde87f42009-06-12 12:55:53 -0700174 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700175 mJournalDir = new File(mBaseStateDir, "pending");
176 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700177 makeJournalLocked(); // okay because no other threads are running yet
178
Christopher Tateabce4e82009-06-18 18:35:32 -0700179 // Build our mapping of uid to backup client services. This implicitly
180 // schedules a backup pass on the Package Manager metadata the first
181 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700182 synchronized (mBackupParticipants) {
183 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700184 }
185
Dan Egnor87a02bc2009-06-17 02:30:10 -0700186 // Set up our transport options and initialize the default transport
187 // TODO: Have transports register themselves somehow?
188 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700189 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700190 ComponentName localName = new ComponentName(context, LocalTransport.class);
191 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700192
Christopher Tate91717492009-06-26 21:07:13 -0700193 mGoogleTransport = null;
194 // !!! TODO: set up the default transport name "the right way"
Christopher Tatece0bf062009-07-01 11:43:53 -0700195 mCurrentTransport = Settings.Secure.getString(mContext.getContentResolver(),
196 BACKUP_TRANSPORT_SETTING);
197 if (mCurrentTransport == null) {
198 mCurrentTransport = "com.google.android.backup/.BackupTransportService";
199 Settings.Secure.putString(mContext.getContentResolver(),
200 BACKUP_TRANSPORT_SETTING, mCurrentTransport);
201 }
Christopher Tate91717492009-06-26 21:07:13 -0700202 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
203
204 // Attach to the Google backup transport. When this comes up, it will set
205 // itself as the current transport because we explicitly reset mCurrentTransport
206 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700207 Intent intent = new Intent().setComponent(new ComponentName(
208 "com.google.android.backup",
209 "com.google.android.backup.BackupTransportService"));
210 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700211
Christopher Tatecde87f42009-06-12 12:55:53 -0700212 // Now that we know about valid backup participants, parse any
213 // leftover journal files and schedule a new backup pass
214 parseLeftoverJournals();
215
Christopher Tate3799bc22009-05-06 16:13:56 -0700216 // Register for broadcasts about package install, etc., so we can
217 // update the provider list.
218 IntentFilter filter = new IntentFilter();
219 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
220 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
221 filter.addDataScheme("package");
222 mContext.registerReceiver(mBroadcastReceiver, filter);
223 }
224
Christopher Tatecde87f42009-06-12 12:55:53 -0700225 private void makeJournalLocked() {
226 try {
227 mJournal = File.createTempFile("journal", null, mJournalDir);
228 mJournalStream = new RandomAccessFile(mJournal, "rwd");
229 } catch (IOException e) {
230 Log.e(TAG, "Unable to write backup journals");
231 mJournal = null;
232 mJournalStream = null;
233 }
234 }
235
236 private void parseLeftoverJournals() {
237 if (mJournal != null) {
238 File[] allJournals = mJournalDir.listFiles();
239 for (File f : allJournals) {
240 if (f.compareTo(mJournal) != 0) {
241 // This isn't the current journal, so it must be a leftover. Read
242 // out the package names mentioned there and schedule them for
243 // backup.
244 try {
245 Log.i(TAG, "Found stale backup journal, scheduling:");
246 RandomAccessFile in = new RandomAccessFile(f, "r");
247 while (true) {
248 String packageName = in.readUTF();
249 Log.i(TAG, " + " + packageName);
250 dataChanged(packageName);
251 }
252 } catch (EOFException e) {
253 // no more data; we're done
254 } catch (Exception e) {
255 // can't read it or other error; just skip it
256 } finally {
257 // close/delete the file
258 f.delete();
259 }
260 }
261 }
262 }
263 }
264
Christopher Tate91717492009-06-26 21:07:13 -0700265 // Add a transport to our set of available backends
266 private void registerTransport(String name, IBackupTransport transport) {
267 synchronized (mTransports) {
268 mTransports.put(name, transport);
269 }
270 }
271
Christopher Tate3799bc22009-05-06 16:13:56 -0700272 // ----- Track installation/removal of packages -----
273 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
274 public void onReceive(Context context, Intent intent) {
275 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
276
277 Uri uri = intent.getData();
278 if (uri == null) {
279 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700280 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700281 String pkgName = uri.getSchemeSpecificPart();
282 if (pkgName == null) {
283 return;
284 }
285
286 String action = intent.getAction();
287 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
288 synchronized (mBackupParticipants) {
289 Bundle extras = intent.getExtras();
290 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
291 // The package was just upgraded
292 updatePackageParticipantsLocked(pkgName);
293 } else {
294 // The package was just added
295 addPackageParticipantsLocked(pkgName);
296 }
297 }
298 }
299 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
300 Bundle extras = intent.getExtras();
301 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
302 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
303 } else {
304 synchronized (mBackupParticipants) {
305 removePackageParticipantsLocked(pkgName);
306 }
307 }
308 }
309 }
310 };
311
Dan Egnor87a02bc2009-06-17 02:30:10 -0700312 // ----- Track connection to GoogleBackupTransport service -----
313 ServiceConnection mGoogleConnection = new ServiceConnection() {
314 public void onServiceConnected(ComponentName name, IBinder service) {
315 if (DEBUG) Log.v(TAG, "Connected to Google transport");
316 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700317 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700318 }
319
320 public void onServiceDisconnected(ComponentName name) {
321 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
322 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700323 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700324 }
325 };
326
Joe Onorato8ad02812009-05-13 01:41:44 -0400327 // ----- Run the actual backup process asynchronously -----
328
Christopher Tate181fafa2009-05-14 11:12:14 -0700329 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400330 public void handleMessage(Message msg) {
331
332 switch (msg.what) {
333 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700334 {
Christopher Tate91717492009-06-26 21:07:13 -0700335 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700336 if (transport == null) {
337 Log.v(TAG, "Backup requested but no transport available");
338 break;
339 }
340
Joe Onorato8ad02812009-05-13 01:41:44 -0400341 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700342 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700343 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400344 synchronized (mQueueLock) {
Christopher Tateace7f092009-06-15 18:07:25 -0700345 if (mPendingBackups.size() == 0) {
346 Log.v(TAG, "Backup requested but nothing pending");
347 break;
348 }
349
Christopher Tate6aa41f42009-06-19 14:14:22 -0700350 for (BackupRequest b: mPendingBackups.values()) {
351 queue.add(b);
Joe Onorato8ad02812009-05-13 01:41:44 -0400352 }
Christopher Tate6aa41f42009-06-19 14:14:22 -0700353 Log.v(TAG, "clearing pending backups");
354 mPendingBackups.clear();
Christopher Tateace7f092009-06-15 18:07:25 -0700355
356 // Start a new backup-queue journal file too
Christopher Tatecde87f42009-06-12 12:55:53 -0700357 if (mJournalStream != null) {
358 try {
359 mJournalStream.close();
360 } catch (IOException e) {
361 // don't need to do anything
362 }
363 makeJournalLocked();
364 }
365
366 // At this point, we have started a new journal file, and the old
367 // file identity is being passed to the backup processing thread.
368 // When it completes successfully, that old journal file will be
369 // deleted. If we crash prior to that, the old journal is parsed
370 // at next boot and the journaled requests fulfilled.
Joe Onorato8ad02812009-05-13 01:41:44 -0400371 }
Dan Egnor87a02bc2009-06-17 02:30:10 -0700372
Christopher Tate6aa41f42009-06-19 14:14:22 -0700373 (new PerformBackupThread(transport, queue, oldJournal)).start();
Christopher Tate043dadc2009-06-02 16:11:00 -0700374 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700375 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700376
377 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400378 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700379
380 case MSG_RUN_RESTORE:
381 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700382 RestoreParams params = (RestoreParams)msg.obj;
Dan Egnor156411d2009-06-26 13:20:02 -0700383 (new PerformRestoreThread(params.transport, params.observer, params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700384 break;
385 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400386 }
387 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400388 }
389
Christopher Tate181fafa2009-05-14 11:12:14 -0700390 // Add the backup agents in the given package to our set of known backup participants.
391 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700392 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700393 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700394 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700395 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700396 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700397 }
398
Christopher Tate181fafa2009-05-14 11:12:14 -0700399 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700400 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700401 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700402 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
403 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700404 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
405 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700406 }
407 }
408
Dan Egnorefe52642009-06-24 00:16:33 -0700409 for (PackageInfo pkg : targetPkgs) {
410 if (packageName == null || pkg.packageName.equals(packageName)) {
411 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700412 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700413 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700414 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700415 mBackupParticipants.put(uid, set);
416 }
Dan Egnorefe52642009-06-24 00:16:33 -0700417 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700418 }
Christopher Tate487529a2009-04-29 14:03:25 -0700419 }
420 }
421
Christopher Tate6785dd82009-06-18 15:58:25 -0700422 // Remove the given package's entry from our known active set. If
423 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700424 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700425 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700426 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700427 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700428 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700429 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700430 int flags = PackageManager.GET_SIGNATURES;
431 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700432 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700433 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700434 }
435 } else {
436 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700437 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700438 }
439 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700440 }
441
Joe Onorato8ad02812009-05-13 01:41:44 -0400442 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700443 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700444 if (DEBUG) {
445 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
446 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700447 for (PackageInfo p : agents) {
448 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700449 }
450 }
Dan Egnorefe52642009-06-24 00:16:33 -0700451 for (PackageInfo pkg : agents) {
452 if (packageName == null || pkg.packageName.equals(packageName)) {
453 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700454 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700455 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700456 // Find the existing entry with the same package name, and remove it.
457 // We can't just remove(app) because the instances are different.
458 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700459 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700460 set.remove(entry);
461 break;
462 }
463 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700464 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700465 mBackupParticipants.delete(uid);
466 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700467 }
468 }
469 }
470 }
471
Christopher Tate181fafa2009-05-14 11:12:14 -0700472 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700473 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700474 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700475 int flags = PackageManager.GET_SIGNATURES;
476 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
477 int N = packages.size();
478 for (int a = N-1; a >= 0; a--) {
479 ApplicationInfo app = packages.get(a).applicationInfo;
480 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
481 || app.backupAgentName == null) {
482 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700483 }
484 }
Dan Egnorefe52642009-06-24 00:16:33 -0700485 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700486 }
Christopher Tateaa088442009-06-16 18:25:46 -0700487
Christopher Tate3799bc22009-05-06 16:13:56 -0700488 // Reset the given package's known backup participants. Unlike add/remove, the update
489 // action cannot be passed a null package name.
490 void updatePackageParticipantsLocked(String packageName) {
491 if (packageName == null) {
492 Log.e(TAG, "updatePackageParticipants called with null package name");
493 return;
494 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700495 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700496
497 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700498 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700499 removePackageParticipantsLockedInner(packageName, allApps);
500 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700501 }
502
Christopher Tate6785dd82009-06-18 15:58:25 -0700503 // The queue lock should be held when scheduling a backup pass
504 private void scheduleBackupPassLocked(long timeFromNowMillis) {
Christopher Tate6ef58a12009-06-29 14:56:28 -0700505 // We only schedule backups when we're actually enabled
506 synchronized (this) {
507 if (mEnabled) {
508 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
509 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, timeFromNowMillis);
510 } else if (DEBUG) {
511 Log.v(TAG, "Disabled, so not scheduling backup pass");
512 }
513 }
Christopher Tate6785dd82009-06-18 15:58:25 -0700514 }
515
Dan Egnor87a02bc2009-06-17 02:30:10 -0700516 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700517 private IBackupTransport getTransport(String transportName) {
518 synchronized (mTransports) {
519 IBackupTransport transport = mTransports.get(transportName);
520 if (transport == null) {
521 Log.w(TAG, "Requested unavailable transport: " + transportName);
522 }
523 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700524 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700525 }
526
Christopher Tatedf01dea2009-06-09 20:45:02 -0700527 // fire off a backup agent, blocking until it attaches or times out
528 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
529 IBackupAgent agent = null;
530 synchronized(mAgentConnectLock) {
531 mConnecting = true;
532 mConnectedAgent = null;
533 try {
534 if (mActivityManager.bindBackupAgent(app, mode)) {
535 Log.d(TAG, "awaiting agent for " + app);
536
537 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700538 // only wait 10 seconds for the clear data to happen
539 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
540 while (mConnecting && mConnectedAgent == null
541 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700542 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700543 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700544 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700545 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700546 return null;
547 }
548 }
549
550 // if we timed out with no connect, abort and move on
551 if (mConnecting == true) {
552 Log.w(TAG, "Timeout waiting for agent " + app);
553 return null;
554 }
555 agent = mConnectedAgent;
556 }
557 } catch (RemoteException e) {
558 // can't happen
559 }
560 }
561 return agent;
562 }
563
Christopher Tatec7b31e32009-06-10 15:49:30 -0700564 // clear an application's data, blocking until the operation completes or times out
565 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700566 // Don't wipe packages marked allowClearUserData=false
567 try {
568 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
569 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
570 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
571 + packageName);
572 return;
573 }
574 } catch (NameNotFoundException e) {
575 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
576 return;
577 }
578
Christopher Tatec7b31e32009-06-10 15:49:30 -0700579 ClearDataObserver observer = new ClearDataObserver();
580
581 synchronized(mClearDataLock) {
582 mClearingData = true;
583 mPackageManager.clearApplicationUserData(packageName, observer);
584
585 // only wait 10 seconds for the clear data to happen
586 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
587 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
588 try {
589 mClearDataLock.wait(5000);
590 } catch (InterruptedException e) {
591 // won't happen, but still.
592 mClearingData = false;
593 }
594 }
595 }
596 }
597
598 class ClearDataObserver extends IPackageDataObserver.Stub {
599 public void onRemoveCompleted(String packageName, boolean succeeded)
600 throws android.os.RemoteException {
601 synchronized(mClearDataLock) {
602 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700603 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700604 }
605 }
606 }
607
Christopher Tate043dadc2009-06-02 16:11:00 -0700608 // ----- Back up a set of applications via a worker thread -----
609
610 class PerformBackupThread extends Thread {
611 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700612 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700613 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700614 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700615 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700616
Christopher Tateaa088442009-06-16 18:25:46 -0700617 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700618 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700619 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700620 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700621 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700622
623 try {
624 mStateDir = new File(mBaseStateDir, transport.transportDirName());
625 } catch (RemoteException e) {
626 // can't happen; the transport is local
627 }
628 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700629 }
630
631 @Override
632 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700633 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
634
Christopher Tate79588342009-06-30 16:11:49 -0700635 // Backups run at background priority
636 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
637
Christopher Tate5cb400b2009-06-25 16:03:14 -0700638 // The package manager doesn't have a proper <application> etc, but since
639 // it's running here in the system process we can just set up its agent
640 // directly and use a synthetic BackupRequest. We always run this pass
641 // because it's cheap and this way we guarantee that we don't get out of
642 // step even if we're selecting among various transports at run time.
643 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
644 mPackageManager, allAgentPackages());
645 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
646 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
647 processOneBackup(pmRequest,
648 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
649 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700650
651 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700652 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700653
654 // Finally, tear down the transport
655 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700656 if (!mTransport.finishBackup()) {
657 // STOPSHIP TODO: handle errors
658 Log.e(TAG, "Backup failure in finishBackup()");
659 }
660 } catch (RemoteException e) {
661 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700662 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700663
664 if (!mJournal.delete()) {
665 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
666 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700667 }
668
669 private void doQueuedBackups(IBackupTransport transport) {
670 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700671 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700672
673 IBackupAgent agent = null;
674 int mode = (request.fullBackup)
675 ? IApplicationThread.BACKUP_MODE_FULL
676 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
677 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700678 agent = bindToAgentSynchronous(request.appInfo, mode);
679 if (agent != null) {
680 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700681 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700682
683 // unbind even on timeout, just in case
684 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700685 } catch (SecurityException ex) {
686 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700687 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700688 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700689 Log.v(TAG, "bind/backup threw");
690 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700691 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700692
Christopher Tate043dadc2009-06-02 16:11:00 -0700693 }
694 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700695
696 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
697 final String packageName = request.appInfo.packageName;
698 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
699
700 try {
701 // Look up the package info & signatures. This is first so that if it
702 // throws an exception, there's no file setup yet that would need to
703 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700704 PackageInfo packInfo;
705 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
706 // The metadata 'package' is synthetic
707 packInfo = new PackageInfo();
708 packInfo.packageName = packageName;
709 } else {
710 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700711 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700712 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700713
714 // !!! TODO: get the state file dir from the transport
715 File savedStateName = new File(mStateDir, packageName);
716 File backupDataName = new File(mDataDir, packageName + ".data");
717 File newStateName = new File(mStateDir, packageName + ".new");
718
719 // In a full backup, we pass a null ParcelFileDescriptor as
720 // the saved-state "file"
721 ParcelFileDescriptor savedState = (request.fullBackup) ? null
722 : ParcelFileDescriptor.open(savedStateName,
723 ParcelFileDescriptor.MODE_READ_ONLY |
724 ParcelFileDescriptor.MODE_CREATE);
725
726 backupDataName.delete();
727 ParcelFileDescriptor backupData =
728 ParcelFileDescriptor.open(backupDataName,
729 ParcelFileDescriptor.MODE_READ_WRITE |
730 ParcelFileDescriptor.MODE_CREATE);
731
732 newStateName.delete();
733 ParcelFileDescriptor newState =
734 ParcelFileDescriptor.open(newStateName,
735 ParcelFileDescriptor.MODE_READ_WRITE |
736 ParcelFileDescriptor.MODE_CREATE);
737
738 // Run the target's backup pass
739 boolean success = false;
740 try {
741 agent.doBackup(savedState, backupData, newState);
742 success = true;
743 } finally {
744 if (savedState != null) {
745 savedState.close();
746 }
747 backupData.close();
748 newState.close();
749 }
750
751 // Now propagate the newly-backed-up data to the transport
752 if (success) {
753 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
754 backupData =
755 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700756 if (!transport.performBackup(packInfo, backupData)) {
757 // STOPSHIP TODO: handle errors
758 Log.e(TAG, "Backup failure in performBackup()");
759 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700760
761 // !!! TODO: After successful transport, delete the now-stale data
762 // and juggle the files so that next time the new state is passed
763 //backupDataName.delete();
764 newStateName.renameTo(savedStateName);
765 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700766 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700767 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700768 }
769 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700770 }
771
Christopher Tatedf01dea2009-06-09 20:45:02 -0700772
773 // ----- Restore handling -----
774
Christopher Tateabce4e82009-06-18 18:35:32 -0700775 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700776 // Allow unsigned apps, but not signed on one device and unsigned on the other
777 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700778 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
779 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700780 if ((storedSigs == null || storedSigs.length == 0)
781 && (deviceSigs == null || deviceSigs.length == 0)) {
782 return true;
783 }
784 if (storedSigs == null || deviceSigs == null) {
785 return false;
786 }
787
Christopher Tateabce4e82009-06-18 18:35:32 -0700788 // !!! TODO: this demands that every stored signature match one
789 // that is present on device, and does not demand the converse.
790 // Is this this right policy?
791 int nStored = storedSigs.length;
792 int nDevice = deviceSigs.length;
793
794 for (int i=0; i < nStored; i++) {
795 boolean match = false;
796 for (int j=0; j < nDevice; j++) {
797 if (storedSigs[i].equals(deviceSigs[j])) {
798 match = true;
799 break;
800 }
801 }
802 if (!match) {
803 return false;
804 }
805 }
806 return true;
807 }
808
Christopher Tatedf01dea2009-06-09 20:45:02 -0700809 class PerformRestoreThread extends Thread {
810 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700811 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700812 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700813 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700814 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700815
Christopher Tate5cbbf562009-06-22 16:44:51 -0700816 class RestoreRequest {
817 public PackageInfo app;
818 public int storedAppVersion;
819
820 RestoreRequest(PackageInfo _app, int _version) {
821 app = _app;
822 storedAppVersion = _version;
823 }
824 }
825
Christopher Tate7d562ec2009-06-25 18:03:43 -0700826 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700827 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700828 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700829 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700830 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700831
832 try {
833 mStateDir = new File(mBaseStateDir, transport.transportDirName());
834 } catch (RemoteException e) {
835 // can't happen; the transport is local
836 }
837 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700838 }
839
840 @Override
841 public void run() {
Christopher Tate6aa41f42009-06-19 14:14:22 -0700842 if (DEBUG) Log.v(TAG, "Beginning restore process");
Christopher Tatedf01dea2009-06-09 20:45:02 -0700843 /**
844 * Restore sequence:
845 *
Dan Egnorefe52642009-06-24 00:16:33 -0700846 * 1. get the restore set description for our identity
847 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700848 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700849 * 3. for each app in the restore queue:
850 * 3.a. clear the app data
851 * 3.b. get the restore data for the app from the transport
852 * 3.c. launch the backup agent for the app
853 * 3.d. agent.doRestore() with the data from the server
854 * 3.e. unbind the agent [and kill the app?]
855 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700856 */
857
Christopher Tate7d562ec2009-06-25 18:03:43 -0700858 int error = -1; // assume error
859
Dan Egnorefe52642009-06-24 00:16:33 -0700860 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700861 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700862 RestoreSet[] images = mTransport.getAvailableRestoreSets();
863 if (images == null) {
864 // STOPSHIP TODO: Handle the failure somehow?
865 Log.e(TAG, "Error getting restore sets");
866 return;
867 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700868
Dan Egnorefe52642009-06-24 00:16:33 -0700869 if (images.length == 0) {
870 Log.i(TAG, "No restore sets available");
871 return;
872 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700873
Dan Egnorefe52642009-06-24 00:16:33 -0700874 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700875
Dan Egnorefe52642009-06-24 00:16:33 -0700876 // Get the list of all packages which have backup enabled.
877 // (Include the Package Manager metadata pseudo-package first.)
878 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
879 PackageInfo omPackage = new PackageInfo();
880 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
881 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700882
Dan Egnorefe52642009-06-24 00:16:33 -0700883 List<PackageInfo> agentPackages = allAgentPackages();
884 restorePackages.addAll(agentPackages);
885
Christopher Tate7d562ec2009-06-25 18:03:43 -0700886 // let the observer know that we're running
887 if (mObserver != null) {
888 try {
889 // !!! TODO: get an actual count from the transport after
890 // its startRestore() runs?
891 mObserver.restoreStarting(restorePackages.size());
892 } catch (RemoteException e) {
893 Log.d(TAG, "Restore observer died at restoreStarting");
894 mObserver = null;
895 }
896 }
897
Dan Egnor156411d2009-06-26 13:20:02 -0700898 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700899 // STOPSHIP TODO: Handle the failure somehow?
900 Log.e(TAG, "Error starting restore operation");
901 return;
902 }
903
904 String packageName = mTransport.nextRestorePackage();
905 if (packageName == null) {
906 // STOPSHIP TODO: Handle the failure somehow?
907 Log.e(TAG, "Error getting first restore package");
908 return;
909 } else if (packageName.equals("")) {
910 Log.i(TAG, "No restore data available");
911 return;
912 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
913 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
914 + "\", found only \"" + packageName + "\"");
915 return;
916 }
917
918 // Pull the Package Manager metadata from the restore set first
919 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
920 mPackageManager, agentPackages);
921 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
922
Christopher Tate7d562ec2009-06-25 18:03:43 -0700923 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700924 for (;;) {
925 packageName = mTransport.nextRestorePackage();
926 if (packageName == null) {
927 // STOPSHIP TODO: Handle the failure somehow?
928 Log.e(TAG, "Error getting next restore package");
929 return;
930 } else if (packageName.equals("")) {
931 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700932 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700933
Christopher Tate7d562ec2009-06-25 18:03:43 -0700934 if (mObserver != null) {
935 ++count;
936 try {
937 mObserver.onUpdate(count);
938 } catch (RemoteException e) {
939 Log.d(TAG, "Restore observer died in onUpdate");
940 mObserver = null;
941 }
942 }
943
Dan Egnorefe52642009-06-24 00:16:33 -0700944 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
945 if (metaInfo == null) {
946 Log.e(TAG, "Missing metadata for " + packageName);
947 continue;
948 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700949
Dan Egnorefe52642009-06-24 00:16:33 -0700950 int flags = PackageManager.GET_SIGNATURES;
951 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
952 if (metaInfo.versionCode > packageInfo.versionCode) {
953 Log.w(TAG, "Package " + packageName
954 + " restore version [" + metaInfo.versionCode
955 + "] is too new for installed version ["
956 + packageInfo.versionCode + "]");
957 continue;
958 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700959
Dan Egnorefe52642009-06-24 00:16:33 -0700960 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
961 Log.w(TAG, "Signature mismatch restoring " + packageName);
962 continue;
963 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700964
Dan Egnorefe52642009-06-24 00:16:33 -0700965 if (DEBUG) Log.v(TAG, "Package " + packageName
966 + " restore version [" + metaInfo.versionCode
967 + "] is compatible with installed version ["
968 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -0700969
Dan Egnorefe52642009-06-24 00:16:33 -0700970 // Now perform the actual restore
971 clearApplicationDataSynchronous(packageName);
972 IBackupAgent agent = bindToAgentSynchronous(
973 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700974 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -0700975 if (agent == null) {
976 Log.w(TAG, "Can't find backup agent for " + packageName);
977 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700978 }
979
Dan Egnorefe52642009-06-24 00:16:33 -0700980 try {
981 processOneRestore(packageInfo, metaInfo.versionCode, agent);
982 } finally {
983 // unbind even on timeout or failure, just in case
984 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
985 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700986 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700987
988 // if we get this far, report success to the observer
989 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700990 } catch (NameNotFoundException e) {
991 // STOPSHIP TODO: Handle the failure somehow?
992 Log.e(TAG, "Invalid paackage restoring data", e);
993 } catch (RemoteException e) {
994 // STOPSHIP TODO: Handle the failure somehow?
995 Log.e(TAG, "Error restoring data", e);
996 } finally {
997 try {
998 mTransport.finishRestore();
999 } catch (RemoteException e) {
1000 Log.e(TAG, "Error finishing restore", e);
1001 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001002
1003 if (mObserver != null) {
1004 try {
1005 mObserver.restoreFinished(error);
1006 } catch (RemoteException e) {
1007 Log.d(TAG, "Restore observer died at restoreFinished");
1008 }
1009 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001010 }
1011 }
1012
Dan Egnorefe52642009-06-24 00:16:33 -07001013 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1014 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001015 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001016 final String packageName = app.packageName;
1017
1018 // !!! TODO: get the dirs from the transport
1019 File backupDataName = new File(mDataDir, packageName + ".restore");
1020 backupDataName.delete();
1021 try {
1022 ParcelFileDescriptor backupData =
1023 ParcelFileDescriptor.open(backupDataName,
1024 ParcelFileDescriptor.MODE_READ_WRITE |
1025 ParcelFileDescriptor.MODE_CREATE);
1026
1027 // Run the transport's restore pass
1028 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001029 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001030 if (!mTransport.getRestoreData(backupData)) {
1031 // STOPSHIP TODO: Handle this error somehow?
1032 Log.e(TAG, "Error getting restore data for " + packageName);
1033 return;
1034 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001035 } finally {
1036 backupData.close();
1037 }
1038
1039 // Okay, we have the data. Now have the agent do the restore.
1040 File newStateName = new File(mStateDir, packageName + ".new");
1041 ParcelFileDescriptor newState =
1042 ParcelFileDescriptor.open(newStateName,
1043 ParcelFileDescriptor.MODE_READ_WRITE |
1044 ParcelFileDescriptor.MODE_CREATE);
1045
1046 backupData = ParcelFileDescriptor.open(backupDataName,
1047 ParcelFileDescriptor.MODE_READ_ONLY);
1048
Christopher Tatec7b31e32009-06-10 15:49:30 -07001049 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001050 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001051 } finally {
1052 newState.close();
1053 backupData.close();
1054 }
1055
1056 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001057 File savedStateName = new File(mStateDir, packageName);
1058 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001059 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001060 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001061 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001062 }
1063 }
1064
1065
Christopher Tate487529a2009-04-29 14:03:25 -07001066 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001067
Christopher Tatea8bf8152009-04-30 11:36:21 -07001068 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001069 // Record that we need a backup pass for the caller. Since multiple callers
1070 // may share a uid, we need to note all candidates within that uid and schedule
1071 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001072
1073 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001074
1075 // If the caller does not hold the BACKUP permission, it can only request a
1076 // backup of its own data.
1077 HashSet<ApplicationInfo> targets;
1078 if ((mContext.checkPermission("android.permission.BACKUP", Binder.getCallingPid(),
1079 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1080 targets = mBackupParticipants.get(Binder.getCallingUid());
1081 } else {
1082 // a caller with full permission can ask to back up any participating app
1083 // !!! TODO: allow backup of ANY app?
1084 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1085 targets = new HashSet<ApplicationInfo>();
1086 int N = mBackupParticipants.size();
1087 for (int i = 0; i < N; i++) {
1088 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1089 if (s != null) {
1090 targets.addAll(s);
1091 }
1092 }
1093 }
Christopher Tate487529a2009-04-29 14:03:25 -07001094 if (targets != null) {
1095 synchronized (mQueueLock) {
1096 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001097 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001098 // validate the caller-supplied package name against the known set of
1099 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001100 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001101 // Add the caller to the set of pending backups. If there is
1102 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001103 BackupRequest req = new BackupRequest(app, false);
1104 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001105
1106 // Journal this request in case of crash
1107 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001108 }
1109 }
1110
Christopher Tate181fafa2009-05-14 11:12:14 -07001111 if (DEBUG) {
1112 int numKeys = mPendingBackups.size();
Christopher Tate6ef58a12009-06-29 14:56:28 -07001113 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate181fafa2009-05-14 11:12:14 -07001114 for (BackupRequest b : mPendingBackups.values()) {
1115 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1116 }
1117 }
Christopher Tate487529a2009-04-29 14:03:25 -07001118 // Schedule a backup pass in a few minutes. As backup-eligible data
1119 // keeps changing, continue to defer the backup pass until things
1120 // settle down, to avoid extra overhead.
Christopher Tate6785dd82009-06-18 15:58:25 -07001121 scheduleBackupPassLocked(COLLECTION_INTERVAL);
Christopher Tate487529a2009-04-29 14:03:25 -07001122 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001123 } else {
1124 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001125 }
1126 }
Christopher Tate46758122009-05-06 11:22:00 -07001127
Christopher Tatecde87f42009-06-12 12:55:53 -07001128 private void writeToJournalLocked(String str) {
1129 if (mJournalStream != null) {
1130 try {
1131 mJournalStream.writeUTF(str);
1132 } catch (IOException e) {
1133 Log.e(TAG, "Error writing to backup journal");
1134 mJournalStream = null;
1135 mJournal = null;
1136 }
1137 }
1138 }
1139
Christopher Tateace7f092009-06-15 18:07:25 -07001140 // Run a backup pass immediately for any applications that have declared
1141 // that they have pending updates.
1142 public void backupNow() throws RemoteException {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001143 mContext.enforceCallingPermission("android.permission.BACKUP", "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001144
Christopher Tateace7f092009-06-15 18:07:25 -07001145 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001146 synchronized (mQueueLock) {
Christopher Tate6785dd82009-06-18 15:58:25 -07001147 scheduleBackupPassLocked(0);
Christopher Tate46758122009-05-06 11:22:00 -07001148 }
1149 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001150
Christopher Tate6ef58a12009-06-29 14:56:28 -07001151 // Enable/disable the backup transport
1152 public void setBackupEnabled(boolean enable) {
1153 mContext.enforceCallingPermission("android.permission.BACKUP", "setBackupEnabled");
1154
1155 boolean wasEnabled = mEnabled;
1156 synchronized (this) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001157 Settings.Secure.putInt(mContext.getContentResolver(), BACKUP_ENABLED_SETTING,
1158 enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001159 mEnabled = enable;
1160 }
1161
1162 if (enable && !wasEnabled) {
1163 synchronized (mQueueLock) {
1164 if (mPendingBackups.size() > 0) {
1165 // !!! TODO: better policy around timing of the first backup pass
1166 if (DEBUG) Log.v(TAG, "Backup enabled with pending data changes, scheduling");
1167 this.scheduleBackupPassLocked(COLLECTION_INTERVAL);
1168 }
1169 }
1170 }
1171}
1172
1173 // Report whether the backup mechanism is currently enabled
1174 public boolean isBackupEnabled() {
1175 mContext.enforceCallingPermission("android.permission.BACKUP", "isBackupEnabled");
1176 return mEnabled; // no need to synchronize just to read it
1177 }
1178
Christopher Tate91717492009-06-26 21:07:13 -07001179 // Report the name of the currently active transport
1180 public String getCurrentTransport() {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001181 mContext.enforceCallingPermission("android.permission.BACKUP", "getCurrentTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001182 Log.v(TAG, "getCurrentTransport() returning " + mCurrentTransport);
1183 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001184 }
1185
Christopher Tate91717492009-06-26 21:07:13 -07001186 // Report all known, available backup transports
1187 public String[] listAllTransports() {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001188 mContext.enforceCallingPermission("android.permission.BACKUP", "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001189
Christopher Tate91717492009-06-26 21:07:13 -07001190 String[] list = null;
1191 ArrayList<String> known = new ArrayList<String>();
1192 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1193 if (entry.getValue() != null) {
1194 known.add(entry.getKey());
1195 }
1196 }
1197
1198 if (known.size() > 0) {
1199 list = new String[known.size()];
1200 known.toArray(list);
1201 }
1202 return list;
1203 }
1204
1205 // Select which transport to use for the next backup operation. If the given
1206 // name is not one of the available transports, no action is taken and the method
1207 // returns null.
1208 public String selectBackupTransport(String transport) {
1209 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
1210
1211 synchronized (mTransports) {
1212 String prevTransport = null;
1213 if (mTransports.get(transport) != null) {
1214 prevTransport = mCurrentTransport;
1215 mCurrentTransport = transport;
Christopher Tatece0bf062009-07-01 11:43:53 -07001216 Settings.Secure.putString(mContext.getContentResolver(), BACKUP_TRANSPORT_SETTING,
1217 transport);
Christopher Tate91717492009-06-26 21:07:13 -07001218 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1219 + " returning " + prevTransport);
1220 } else {
1221 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1222 }
1223 return prevTransport;
1224 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001225 }
1226
1227 // Callback: a requested backup agent has been instantiated. This should only
1228 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001229 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001230 synchronized(mAgentConnectLock) {
1231 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1232 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1233 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1234 mConnectedAgent = agent;
1235 mConnecting = false;
1236 } else {
1237 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1238 + " claiming agent connected");
1239 }
1240 mAgentConnectLock.notifyAll();
1241 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001242 }
1243
1244 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1245 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001246 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001247 public void agentDisconnected(String packageName) {
1248 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001249 synchronized(mAgentConnectLock) {
1250 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1251 mConnectedAgent = null;
1252 mConnecting = false;
1253 } else {
1254 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1255 + " claiming agent disconnected");
1256 }
1257 mAgentConnectLock.notifyAll();
1258 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001259 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001260
Christopher Tate8c850b72009-06-07 19:33:20 -07001261 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001262 public IRestoreSession beginRestoreSession(String transport) {
Christopher Tate8c850b72009-06-07 19:33:20 -07001263 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001264
1265 synchronized(this) {
1266 if (mActiveRestoreSession != null) {
1267 Log.d(TAG, "Restore session requested but one already active");
1268 return null;
1269 }
Christopher Tate91717492009-06-26 21:07:13 -07001270 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001271 }
1272 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001273 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001274
Christopher Tate9b3905c2009-06-08 15:24:01 -07001275 // ----- Restore session -----
1276
1277 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001278 private static final String TAG = "RestoreSession";
1279
Christopher Tate9b3905c2009-06-08 15:24:01 -07001280 private IBackupTransport mRestoreTransport = null;
1281 RestoreSet[] mRestoreSets = null;
1282
Christopher Tate91717492009-06-26 21:07:13 -07001283 RestoreSession(String transport) {
1284 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001285 }
1286
1287 // --- Binder interface ---
1288 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001289 mContext.enforceCallingPermission("android.permission.BACKUP",
1290 "getAvailableRestoreSets");
1291
Christopher Tatef68eb502009-06-16 11:02:01 -07001292 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001293 synchronized(this) {
1294 if (mRestoreSets == null) {
1295 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1296 }
1297 return mRestoreSets;
1298 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001299 } catch (RuntimeException e) {
1300 Log.d(TAG, "getAvailableRestoreSets exception");
1301 e.printStackTrace();
1302 throw e;
1303 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001304 }
1305
Dan Egnor156411d2009-06-26 13:20:02 -07001306 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001307 throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001308 mContext.enforceCallingPermission("android.permission.BACKUP", "performRestore");
1309
1310 if (mRestoreSets != null) {
1311 for (int i = 0; i < mRestoreSets.length; i++) {
1312 if (token == mRestoreSets[i].token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001313 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001314 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001315 mBackupHandler.sendMessage(msg);
1316 return 0;
1317 }
1318 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001319 } else {
1320 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001321 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001322 return -1;
1323 }
1324
1325 public void endRestoreSession() throws android.os.RemoteException {
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001326 mContext.enforceCallingPermission("android.permission.BACKUP",
1327 "endRestoreSession");
1328
Dan Egnorefe52642009-06-24 00:16:33 -07001329 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001330 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001331 synchronized(BackupManagerService.this) {
1332 if (BackupManagerService.this.mActiveRestoreSession == this) {
1333 BackupManagerService.this.mActiveRestoreSession = null;
1334 } else {
1335 Log.e(TAG, "ending non-current restore session");
1336 }
1337 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001338 }
1339 }
1340
Christopher Tate043dadc2009-06-02 16:11:00 -07001341
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001342 @Override
1343 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1344 synchronized (mQueueLock) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001345 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled"));
Christopher Tate91717492009-06-26 21:07:13 -07001346 pw.println("Available transports:");
1347 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001348 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1349 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001350 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001351 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001352 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001353 for (int i=0; i<N; i++) {
1354 int uid = mBackupParticipants.keyAt(i);
1355 pw.print(" uid: ");
1356 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001357 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1358 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001359 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001360 }
1361 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001362 pw.println("Pending: " + mPendingBackups.size());
1363 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001364 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001365 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001366 }
1367 }
Christopher Tate487529a2009-04-29 14:03:25 -07001368}