blob: 6eba783c8340cc9a6d75f182d0e0994ec6ee9bd0 [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;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070021import android.app.IActivityManager;
22import android.app.IApplicationThread;
23import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070024import android.app.PendingIntent;
Christopher Tate3799bc22009-05-06 16:13:56 -070025import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070026import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070027import android.content.Context;
28import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070029import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070030import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070031import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070032import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070033import android.content.pm.PackageInfo;
Christopher Tate043dadc2009-06-02 16:11:00 -070034import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070036import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070037import android.net.Uri;
Christopher Tatece0bf062009-07-01 11:43:53 -070038import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070039import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070041import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070042import android.os.Handler;
43import android.os.IBinder;
44import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070045import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070046import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070047import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.RemoteException;
49import android.util.Log;
50import android.util.SparseArray;
51
52import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070053import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070054import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070055import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070056
Christopher Tate9bbc21a2009-06-10 20:23:25 -070057import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070058import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070059
Christopher Tate6785dd82009-06-18 15:58:25 -070060import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070061import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070062
Christopher Tatecde87f42009-06-12 12:55:53 -070063import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070064import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070065import java.io.FileDescriptor;
Christopher Tatec7b31e32009-06-10 15:49:30 -070066import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070067import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070068import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070069import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040070import java.util.ArrayList;
71import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070072import java.util.HashSet;
73import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070074import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070075
76class BackupManagerService extends IBackupManager.Stub {
77 private static final String TAG = "BackupManagerService";
78 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070079
Christopher Tate49401dd2009-07-01 12:34:29 -070080 // How often we perform a backup pass. Privileged external callers can
81 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070082 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070083
Christopher Tate8031a3d2009-07-06 16:36:05 -070084 // The amount of time between the initial provisioning of the device and
85 // the first backup pass.
86 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
87
Christopher Tateb6787f22009-07-02 17:40:45 -070088 private static final String RUN_BACKUP_ACTION = "_backup_run_";
Christopher Tate487529a2009-04-29 14:03:25 -070089 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070090 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070091 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070092 private static final int MSG_RUN_CLEAR = 4;
Christopher Tatec7b31e32009-06-10 15:49:30 -070093
94 // Timeout interval for deciding that a bind or clear-data has taken too long
95 static final long TIMEOUT_INTERVAL = 10 * 1000;
96
Christopher Tate487529a2009-04-29 14:03:25 -070097 private Context mContext;
98 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -070099 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700100 private PowerManager mPowerManager;
101 private AlarmManager mAlarmManager;
102
Christopher Tate73e02522009-07-15 14:18:26 -0700103 boolean mEnabled; // access to this is synchronized on 'this'
104 boolean mProvisioned;
105 PowerManager.WakeLock mWakelock;
106 final BackupHandler mBackupHandler = new BackupHandler();
107 PendingIntent mRunBackupIntent;
108 BroadcastReceiver mRunBackupReceiver;
109 IntentFilter mRunBackupFilter;
Christopher Tate487529a2009-04-29 14:03:25 -0700110 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700111 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700112 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700113 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700114 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700115 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700116 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700117
Christopher Tate181fafa2009-05-14 11:12:14 -0700118 BackupRequest(ApplicationInfo app, boolean isFull) {
119 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700120 fullBackup = isFull;
121 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700122
123 public String toString() {
124 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
125 }
Christopher Tate46758122009-05-06 11:22:00 -0700126 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400127 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700128 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700129 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700130
131 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700132 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700133
134 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700135 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700136
Christopher Tate043dadc2009-06-02 16:11:00 -0700137 // The thread performing the sequence of queued backups binds to each app's agent
138 // in succession. Bind notifications are asynchronously delivered through the
139 // Activity Manager; use this lock object to signal when a requested binding has
140 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700141 final Object mAgentConnectLock = new Object();
142 IBackupAgent mConnectedAgent;
143 volatile boolean mConnecting;
Christopher Tate043dadc2009-06-02 16:11:00 -0700144
Christopher Tatec7b31e32009-06-10 15:49:30 -0700145 // A similar synchronicity mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700146 final Object mClearDataLock = new Object();
147 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700148
Christopher Tate91717492009-06-26 21:07:13 -0700149 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700150 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700151 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700152 String mCurrentTransport;
153 IBackupTransport mLocalTransport, mGoogleTransport;
154 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700155
Christopher Tate73e02522009-07-15 14:18:26 -0700156 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700157 public IBackupTransport transport;
158 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700159 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700160
Dan Egnor156411d2009-06-26 13:20:02 -0700161 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700162 transport = _transport;
163 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700164 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700165 }
166 }
167
Christopher Tate73e02522009-07-15 14:18:26 -0700168 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700169 public IBackupTransport transport;
170 public PackageInfo packageInfo;
171
172 ClearParams(IBackupTransport _transport, PackageInfo _info) {
173 transport = _transport;
174 packageInfo = _info;
175 }
176 }
177
Christopher Tate5cb400b2009-06-25 16:03:14 -0700178 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700179 File mBaseStateDir;
180 File mDataDir;
181 File mJournalDir;
182 File mJournal;
183 RandomAccessFile mJournalStream;
184
185 // Keep a log of all the apps we've ever backed up
186 private File mEverStored;
187 private RandomAccessFile mEverStoredStream;
188 HashSet<String> mEverStoredApps = new HashSet<String>();
189
Christopher Tateaa088442009-06-16 18:25:46 -0700190
Christopher Tate487529a2009-04-29 14:03:25 -0700191 public BackupManagerService(Context context) {
192 mContext = context;
193 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700194 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700195
Christopher Tateb6787f22009-07-02 17:40:45 -0700196 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
197 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
198
Christopher Tate22b87872009-05-04 16:41:53 -0700199 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700200 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700201 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700202 // !!! TODO: mProvisioned needs to default to 0, not 1.
203 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
204 Settings.Secure.BACKUP_PROVISIONED, 1) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700205 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700206 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700207
Christopher Tateb6787f22009-07-02 17:40:45 -0700208 mRunBackupReceiver = new RunBackupReceiver();
209 mRunBackupFilter = new IntentFilter();
210 mRunBackupFilter.addAction(RUN_BACKUP_ACTION);
211 context.registerReceiver(mRunBackupReceiver, mRunBackupFilter);
212
213 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
214 // !!! TODO: restrict delivery to our receiver; the naive setClass() doesn't seem to work
215 //backupIntent.setClass(context, mRunBackupReceiver.getClass());
216 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
217 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
218
Christopher Tatecde87f42009-06-12 12:55:53 -0700219 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700220 mJournalDir = new File(mBaseStateDir, "pending");
221 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700222 makeJournalLocked(); // okay because no other threads are running yet
223
Christopher Tate73e02522009-07-15 14:18:26 -0700224 // Set up the various sorts of package tracking we do
225 initPackageTracking();
226
Christopher Tateabce4e82009-06-18 18:35:32 -0700227 // Build our mapping of uid to backup client services. This implicitly
228 // schedules a backup pass on the Package Manager metadata the first
229 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700230 synchronized (mBackupParticipants) {
231 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700232 }
233
Dan Egnor87a02bc2009-06-17 02:30:10 -0700234 // Set up our transport options and initialize the default transport
235 // TODO: Have transports register themselves somehow?
236 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700237 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700238 ComponentName localName = new ComponentName(context, LocalTransport.class);
239 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700240
Christopher Tate91717492009-06-26 21:07:13 -0700241 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700242 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
243 Settings.Secure.BACKUP_TRANSPORT);
244 if ("".equals(mCurrentTransport)) {
245 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700246 }
Christopher Tate91717492009-06-26 21:07:13 -0700247 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
248
249 // Attach to the Google backup transport. When this comes up, it will set
250 // itself as the current transport because we explicitly reset mCurrentTransport
251 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700252 Intent intent = new Intent().setComponent(new ComponentName(
253 "com.google.android.backup",
254 "com.google.android.backup.BackupTransportService"));
255 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700256
Christopher Tatecde87f42009-06-12 12:55:53 -0700257 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700258 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700259 parseLeftoverJournals();
260
Christopher Tateb6787f22009-07-02 17:40:45 -0700261 // Power management
262 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
263
264 // Start the backup passes going
265 setBackupEnabled(areEnabled);
266 }
267
268 private class RunBackupReceiver extends BroadcastReceiver {
269 public void onReceive(Context context, Intent intent) {
270 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
271 if (DEBUG) Log.v(TAG, "Running a backup pass");
272
273 synchronized (mQueueLock) {
274 // acquire a wakelock and pass it to the backup thread. it will
275 // be released once backup concludes.
276 mWakelock.acquire();
277
278 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
279 mBackupHandler.sendMessage(msg);
280 }
281 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700282 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700283 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700284
Christopher Tate73e02522009-07-15 14:18:26 -0700285 private void initPackageTracking() {
286 if (DEBUG) Log.v(TAG, "Initializing package tracking");
287
288 // Keep a log of what apps we've ever backed up
289 mEverStored = new File(mBaseStateDir, "processed");
290 try {
291 mEverStoredStream = new RandomAccessFile(mEverStored, "rwd");
292
293 // parse its existing contents
294 mEverStoredStream.seek(0);
295 try {
296 while (true) {
297 String pkg = mEverStoredStream.readUTF();
298 mEverStoredApps.add(pkg);
299 if (DEBUG) Log.v(TAG, " + " + pkg);
300 }
301 } catch (EOFException e) {
302 // now we're at EOF
303 }
304 } catch (IOException e) {
305 Log.e(TAG, "Unable to open known-stored file!");
306 mEverStoredStream = null;
307 }
308
309 // Register for broadcasts about package install, etc., so we can
310 // update the provider list.
311 IntentFilter filter = new IntentFilter();
312 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
313 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
314 filter.addDataScheme("package");
315 mContext.registerReceiver(mBroadcastReceiver, filter);
316 }
317
Christopher Tatecde87f42009-06-12 12:55:53 -0700318 private void makeJournalLocked() {
319 try {
320 mJournal = File.createTempFile("journal", null, mJournalDir);
321 mJournalStream = new RandomAccessFile(mJournal, "rwd");
322 } catch (IOException e) {
323 Log.e(TAG, "Unable to write backup journals");
324 mJournal = null;
325 mJournalStream = null;
326 }
327 }
328
329 private void parseLeftoverJournals() {
330 if (mJournal != null) {
331 File[] allJournals = mJournalDir.listFiles();
332 for (File f : allJournals) {
333 if (f.compareTo(mJournal) != 0) {
334 // This isn't the current journal, so it must be a leftover. Read
335 // out the package names mentioned there and schedule them for
336 // backup.
337 try {
338 Log.i(TAG, "Found stale backup journal, scheduling:");
339 RandomAccessFile in = new RandomAccessFile(f, "r");
340 while (true) {
341 String packageName = in.readUTF();
342 Log.i(TAG, " + " + packageName);
343 dataChanged(packageName);
344 }
345 } catch (EOFException e) {
346 // no more data; we're done
347 } catch (Exception e) {
348 // can't read it or other error; just skip it
349 } finally {
350 // close/delete the file
351 f.delete();
352 }
353 }
354 }
355 }
356 }
357
Christopher Tate91717492009-06-26 21:07:13 -0700358 // Add a transport to our set of available backends
359 private void registerTransport(String name, IBackupTransport transport) {
360 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700361 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700362 mTransports.put(name, transport);
363 }
364 }
365
Christopher Tate3799bc22009-05-06 16:13:56 -0700366 // ----- Track installation/removal of packages -----
367 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
368 public void onReceive(Context context, Intent intent) {
369 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
370
371 Uri uri = intent.getData();
372 if (uri == null) {
373 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700374 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700375 String pkgName = uri.getSchemeSpecificPart();
376 if (pkgName == null) {
377 return;
378 }
379
380 String action = intent.getAction();
381 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
382 synchronized (mBackupParticipants) {
383 Bundle extras = intent.getExtras();
384 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
385 // The package was just upgraded
386 updatePackageParticipantsLocked(pkgName);
387 } else {
388 // The package was just added
389 addPackageParticipantsLocked(pkgName);
390 }
391 }
392 }
393 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
394 Bundle extras = intent.getExtras();
395 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
396 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
397 } else {
398 synchronized (mBackupParticipants) {
399 removePackageParticipantsLocked(pkgName);
400 }
401 }
402 }
403 }
404 };
405
Dan Egnor87a02bc2009-06-17 02:30:10 -0700406 // ----- Track connection to GoogleBackupTransport service -----
407 ServiceConnection mGoogleConnection = new ServiceConnection() {
408 public void onServiceConnected(ComponentName name, IBinder service) {
409 if (DEBUG) Log.v(TAG, "Connected to Google transport");
410 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700411 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700412 }
413
414 public void onServiceDisconnected(ComponentName name) {
415 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
416 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700417 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700418 }
419 };
420
Joe Onorato8ad02812009-05-13 01:41:44 -0400421 // ----- Run the actual backup process asynchronously -----
422
Christopher Tate181fafa2009-05-14 11:12:14 -0700423 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400424 public void handleMessage(Message msg) {
425
426 switch (msg.what) {
427 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700428 {
Christopher Tate91717492009-06-26 21:07:13 -0700429 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700430 if (transport == null) {
431 Log.v(TAG, "Backup requested but no transport available");
Christopher Tateb6787f22009-07-02 17:40:45 -0700432 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700433 break;
434 }
435
Joe Onorato8ad02812009-05-13 01:41:44 -0400436 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700437 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700438 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400439 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700440 // Do we have any work to do?
441 if (mPendingBackups.size() > 0) {
442 for (BackupRequest b: mPendingBackups.values()) {
443 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700444 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700445 Log.v(TAG, "clearing pending backups");
446 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700447
Christopher Tate49401dd2009-07-01 12:34:29 -0700448 // Start a new backup-queue journal file too
449 if (mJournalStream != null) {
450 try {
451 mJournalStream.close();
452 } catch (IOException e) {
453 // don't need to do anything
454 }
455 makeJournalLocked();
456 }
457
458 // At this point, we have started a new journal file, and the old
459 // file identity is being passed to the backup processing thread.
460 // When it completes successfully, that old journal file will be
461 // deleted. If we crash prior to that, the old journal is parsed
462 // at next boot and the journaled requests fulfilled.
463 (new PerformBackupThread(transport, queue, oldJournal)).start();
464 } else {
465 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700466 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700467 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400468 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700469 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700470 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700471
472 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400473 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700474
475 case MSG_RUN_RESTORE:
476 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700477 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400478 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700479 (new PerformRestoreThread(params.transport, params.observer,
480 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700481 break;
482 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700483
484 case MSG_RUN_CLEAR:
485 {
486 ClearParams params = (ClearParams)msg.obj;
487 (new PerformClearThread(params.transport, params.packageInfo)).start();
488 break;
489 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400490 }
491 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400492 }
493
Christopher Tate181fafa2009-05-14 11:12:14 -0700494 // Add the backup agents in the given package to our set of known backup participants.
495 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700496 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700497 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700498 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700499 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700500 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700501 }
502
Christopher Tate181fafa2009-05-14 11:12:14 -0700503 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700504 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700505 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700506 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
507 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700508 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
509 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700510 }
511 }
512
Dan Egnorefe52642009-06-24 00:16:33 -0700513 for (PackageInfo pkg : targetPkgs) {
514 if (packageName == null || pkg.packageName.equals(packageName)) {
515 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700516 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700517 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700518 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700519 mBackupParticipants.put(uid, set);
520 }
Dan Egnorefe52642009-06-24 00:16:33 -0700521 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700522
523 // If we've never seen this app before, schedule a backup for it
524 if (!mEverStoredApps.contains(pkg.packageName)) {
525 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
526 + " never backed up; scheduling");
527 try {
528 dataChanged(pkg.packageName);
529 } catch (RemoteException e) {
530 // can't happen; it's a local method call
531 }
532 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700533 }
Christopher Tate487529a2009-04-29 14:03:25 -0700534 }
535 }
536
Christopher Tate6785dd82009-06-18 15:58:25 -0700537 // Remove the given package's entry from our known active set. If
538 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700539 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700540 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700541 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700542 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700543 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700544 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700545 int flags = PackageManager.GET_SIGNATURES;
546 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700547 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700548 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700549 }
550 } else {
551 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700552 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700553 }
554 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700555 }
556
Joe Onorato8ad02812009-05-13 01:41:44 -0400557 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700558 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700559 if (DEBUG) {
560 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
561 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700562 for (PackageInfo p : agents) {
563 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700564 }
565 }
Dan Egnorefe52642009-06-24 00:16:33 -0700566 for (PackageInfo pkg : agents) {
567 if (packageName == null || pkg.packageName.equals(packageName)) {
568 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700569 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700570 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700571 // Find the existing entry with the same package name, and remove it.
572 // We can't just remove(app) because the instances are different.
573 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700574 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700575 set.remove(entry);
576 break;
577 }
578 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700579 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700580 mBackupParticipants.delete(uid);
581 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700582 }
583 }
584 }
585 }
586
Christopher Tate181fafa2009-05-14 11:12:14 -0700587 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700588 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700589 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700590 int flags = PackageManager.GET_SIGNATURES;
591 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
592 int N = packages.size();
593 for (int a = N-1; a >= 0; a--) {
594 ApplicationInfo app = packages.get(a).applicationInfo;
595 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
596 || app.backupAgentName == null) {
597 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700598 }
599 }
Dan Egnorefe52642009-06-24 00:16:33 -0700600 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700601 }
Christopher Tateaa088442009-06-16 18:25:46 -0700602
Christopher Tate3799bc22009-05-06 16:13:56 -0700603 // Reset the given package's known backup participants. Unlike add/remove, the update
604 // action cannot be passed a null package name.
605 void updatePackageParticipantsLocked(String packageName) {
606 if (packageName == null) {
607 Log.e(TAG, "updatePackageParticipants called with null package name");
608 return;
609 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700610 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700611
612 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700613 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700614 removePackageParticipantsLockedInner(packageName, allApps);
615 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700616 }
617
Christopher Tate73e02522009-07-15 14:18:26 -0700618 // Called from the backup thread: record that the given app has been successfully
619 // backed up at least once
620 void logBackupComplete(String packageName) {
621 if (mEverStoredStream != null) {
622 synchronized (mEverStoredApps) {
623 if (mEverStoredApps.add(packageName)) {
624 try {
625 mEverStoredStream.writeUTF(packageName);
626 } catch (IOException e) {
627 Log.e(TAG, "Unable to log backup of " + packageName + ", ceasing log");
628 try {
629 mEverStoredStream.close();
630 } catch (IOException ioe) {
631 // we're dropping it; no need to handle an exception on close here
632 }
633 mEverStoredStream = null;
634 }
635 }
636 }
637 }
638 }
639
Dan Egnor87a02bc2009-06-17 02:30:10 -0700640 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700641 private IBackupTransport getTransport(String transportName) {
642 synchronized (mTransports) {
643 IBackupTransport transport = mTransports.get(transportName);
644 if (transport == null) {
645 Log.w(TAG, "Requested unavailable transport: " + transportName);
646 }
647 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700648 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700649 }
650
Christopher Tatedf01dea2009-06-09 20:45:02 -0700651 // fire off a backup agent, blocking until it attaches or times out
652 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
653 IBackupAgent agent = null;
654 synchronized(mAgentConnectLock) {
655 mConnecting = true;
656 mConnectedAgent = null;
657 try {
658 if (mActivityManager.bindBackupAgent(app, mode)) {
659 Log.d(TAG, "awaiting agent for " + app);
660
661 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700662 // only wait 10 seconds for the clear data to happen
663 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
664 while (mConnecting && mConnectedAgent == null
665 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700666 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700667 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700668 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700669 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700670 return null;
671 }
672 }
673
674 // if we timed out with no connect, abort and move on
675 if (mConnecting == true) {
676 Log.w(TAG, "Timeout waiting for agent " + app);
677 return null;
678 }
679 agent = mConnectedAgent;
680 }
681 } catch (RemoteException e) {
682 // can't happen
683 }
684 }
685 return agent;
686 }
687
Christopher Tatec7b31e32009-06-10 15:49:30 -0700688 // clear an application's data, blocking until the operation completes or times out
689 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700690 // Don't wipe packages marked allowClearUserData=false
691 try {
692 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
693 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
694 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
695 + packageName);
696 return;
697 }
698 } catch (NameNotFoundException e) {
699 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
700 return;
701 }
702
Christopher Tatec7b31e32009-06-10 15:49:30 -0700703 ClearDataObserver observer = new ClearDataObserver();
704
705 synchronized(mClearDataLock) {
706 mClearingData = true;
707 mPackageManager.clearApplicationUserData(packageName, observer);
708
709 // only wait 10 seconds for the clear data to happen
710 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
711 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
712 try {
713 mClearDataLock.wait(5000);
714 } catch (InterruptedException e) {
715 // won't happen, but still.
716 mClearingData = false;
717 }
718 }
719 }
720 }
721
722 class ClearDataObserver extends IPackageDataObserver.Stub {
723 public void onRemoveCompleted(String packageName, boolean succeeded)
724 throws android.os.RemoteException {
725 synchronized(mClearDataLock) {
726 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700727 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700728 }
729 }
730 }
731
Christopher Tate043dadc2009-06-02 16:11:00 -0700732 // ----- Back up a set of applications via a worker thread -----
733
734 class PerformBackupThread extends Thread {
735 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700736 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700737 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700738 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700739 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700740
Christopher Tateaa088442009-06-16 18:25:46 -0700741 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700742 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700743 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700744 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700745 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700746
747 try {
748 mStateDir = new File(mBaseStateDir, transport.transportDirName());
749 } catch (RemoteException e) {
750 // can't happen; the transport is local
751 }
752 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700753 }
754
755 @Override
756 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700757 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
758
Christopher Tate79588342009-06-30 16:11:49 -0700759 // Backups run at background priority
760 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
761
Christopher Tate5cb400b2009-06-25 16:03:14 -0700762 // The package manager doesn't have a proper <application> etc, but since
763 // it's running here in the system process we can just set up its agent
764 // directly and use a synthetic BackupRequest. We always run this pass
765 // because it's cheap and this way we guarantee that we don't get out of
766 // step even if we're selecting among various transports at run time.
767 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
768 mPackageManager, allAgentPackages());
769 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
770 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
771 processOneBackup(pmRequest,
772 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
773 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700774
775 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700776 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700777
778 // Finally, tear down the transport
779 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700780 if (!mTransport.finishBackup()) {
781 // STOPSHIP TODO: handle errors
782 Log.e(TAG, "Backup failure in finishBackup()");
783 }
784 } catch (RemoteException e) {
785 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700786 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700787
788 if (!mJournal.delete()) {
789 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
790 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700791
792 // Only once we're entirely finished do we release the wakelock
793 mWakelock.release();
Christopher Tate043dadc2009-06-02 16:11:00 -0700794 }
795
796 private void doQueuedBackups(IBackupTransport transport) {
797 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700798 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700799
800 IBackupAgent agent = null;
801 int mode = (request.fullBackup)
802 ? IApplicationThread.BACKUP_MODE_FULL
803 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
804 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700805 agent = bindToAgentSynchronous(request.appInfo, mode);
806 if (agent != null) {
807 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700808 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700809
810 // unbind even on timeout, just in case
811 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700812 } catch (SecurityException ex) {
813 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700814 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700815 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700816 Log.v(TAG, "bind/backup threw");
817 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700818 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700819
Christopher Tate043dadc2009-06-02 16:11:00 -0700820 }
821 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700822
823 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
824 final String packageName = request.appInfo.packageName;
825 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
826
827 try {
828 // Look up the package info & signatures. This is first so that if it
829 // throws an exception, there's no file setup yet that would need to
830 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700831 PackageInfo packInfo;
832 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
833 // The metadata 'package' is synthetic
834 packInfo = new PackageInfo();
835 packInfo.packageName = packageName;
836 } else {
837 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700838 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700839 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700840
841 // !!! TODO: get the state file dir from the transport
842 File savedStateName = new File(mStateDir, packageName);
843 File backupDataName = new File(mDataDir, packageName + ".data");
844 File newStateName = new File(mStateDir, packageName + ".new");
845
846 // In a full backup, we pass a null ParcelFileDescriptor as
847 // the saved-state "file"
848 ParcelFileDescriptor savedState = (request.fullBackup) ? null
849 : ParcelFileDescriptor.open(savedStateName,
850 ParcelFileDescriptor.MODE_READ_ONLY |
851 ParcelFileDescriptor.MODE_CREATE);
852
853 backupDataName.delete();
854 ParcelFileDescriptor backupData =
855 ParcelFileDescriptor.open(backupDataName,
856 ParcelFileDescriptor.MODE_READ_WRITE |
857 ParcelFileDescriptor.MODE_CREATE);
858
859 newStateName.delete();
860 ParcelFileDescriptor newState =
861 ParcelFileDescriptor.open(newStateName,
862 ParcelFileDescriptor.MODE_READ_WRITE |
863 ParcelFileDescriptor.MODE_CREATE);
864
865 // Run the target's backup pass
866 boolean success = false;
867 try {
868 agent.doBackup(savedState, backupData, newState);
Christopher Tate73e02522009-07-15 14:18:26 -0700869 logBackupComplete(packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700870 success = true;
871 } finally {
872 if (savedState != null) {
873 savedState.close();
874 }
875 backupData.close();
876 newState.close();
877 }
878
879 // Now propagate the newly-backed-up data to the transport
880 if (success) {
Christopher Tateb407f222009-07-08 13:48:56 -0700881 if (DEBUG) Log.v(TAG, "doBackup() success");
882 if (backupDataName.length() > 0) {
883 backupData =
884 ParcelFileDescriptor.open(backupDataName,
885 ParcelFileDescriptor.MODE_READ_ONLY);
886 if (!transport.performBackup(packInfo, backupData)) {
887 // STOPSHIP TODO: handle errors
888 Log.e(TAG, "Backup failure in performBackup()");
889 }
890 } else {
891 if (DEBUG) {
892 Log.i(TAG, "no backup data written; not calling transport");
893 }
Dan Egnorefe52642009-06-24 00:16:33 -0700894 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700895
Christopher Tateb407f222009-07-08 13:48:56 -0700896 // After successful transport, delete the now-stale data
897 // and juggle the files so that next time we supply the agent
898 // with the new state file it just created.
899 backupDataName.delete();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700900 newStateName.renameTo(savedStateName);
901 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700902 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700903 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700904 }
905 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700906 }
907
Christopher Tatedf01dea2009-06-09 20:45:02 -0700908
909 // ----- Restore handling -----
910
Christopher Tateabce4e82009-06-18 18:35:32 -0700911 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700912 // Allow unsigned apps, but not signed on one device and unsigned on the other
913 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700914 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
915 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700916 if ((storedSigs == null || storedSigs.length == 0)
917 && (deviceSigs == null || deviceSigs.length == 0)) {
918 return true;
919 }
920 if (storedSigs == null || deviceSigs == null) {
921 return false;
922 }
923
Christopher Tateabce4e82009-06-18 18:35:32 -0700924 // !!! TODO: this demands that every stored signature match one
925 // that is present on device, and does not demand the converse.
926 // Is this this right policy?
927 int nStored = storedSigs.length;
928 int nDevice = deviceSigs.length;
929
930 for (int i=0; i < nStored; i++) {
931 boolean match = false;
932 for (int j=0; j < nDevice; j++) {
933 if (storedSigs[i].equals(deviceSigs[j])) {
934 match = true;
935 break;
936 }
937 }
938 if (!match) {
939 return false;
940 }
941 }
942 return true;
943 }
944
Christopher Tatedf01dea2009-06-09 20:45:02 -0700945 class PerformRestoreThread extends Thread {
946 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700947 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700948 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700949 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700950 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700951
Christopher Tate5cbbf562009-06-22 16:44:51 -0700952 class RestoreRequest {
953 public PackageInfo app;
954 public int storedAppVersion;
955
956 RestoreRequest(PackageInfo _app, int _version) {
957 app = _app;
958 storedAppVersion = _version;
959 }
960 }
961
Christopher Tate7d562ec2009-06-25 18:03:43 -0700962 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700963 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700964 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400965 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -0700966 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700967 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700968
969 try {
970 mStateDir = new File(mBaseStateDir, transport.transportDirName());
971 } catch (RemoteException e) {
972 // can't happen; the transport is local
973 }
974 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700975 }
976
977 @Override
978 public void run() {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400979 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
980 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700981 /**
982 * Restore sequence:
983 *
Dan Egnorefe52642009-06-24 00:16:33 -0700984 * 1. get the restore set description for our identity
985 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700986 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700987 * 3. for each app in the restore queue:
988 * 3.a. clear the app data
989 * 3.b. get the restore data for the app from the transport
990 * 3.c. launch the backup agent for the app
991 * 3.d. agent.doRestore() with the data from the server
992 * 3.e. unbind the agent [and kill the app?]
993 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700994 */
995
Christopher Tate7d562ec2009-06-25 18:03:43 -0700996 int error = -1; // assume error
997
Dan Egnorefe52642009-06-24 00:16:33 -0700998 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700999 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001000 RestoreSet[] images = mTransport.getAvailableRestoreSets();
1001 if (images == null) {
1002 // STOPSHIP TODO: Handle the failure somehow?
1003 Log.e(TAG, "Error getting restore sets");
1004 return;
1005 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001006
Dan Egnorefe52642009-06-24 00:16:33 -07001007 if (images.length == 0) {
1008 Log.i(TAG, "No restore sets available");
1009 return;
1010 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001011
Dan Egnorefe52642009-06-24 00:16:33 -07001012 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -07001013
Dan Egnorefe52642009-06-24 00:16:33 -07001014 // Get the list of all packages which have backup enabled.
1015 // (Include the Package Manager metadata pseudo-package first.)
1016 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1017 PackageInfo omPackage = new PackageInfo();
1018 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1019 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001020
Dan Egnorefe52642009-06-24 00:16:33 -07001021 List<PackageInfo> agentPackages = allAgentPackages();
1022 restorePackages.addAll(agentPackages);
1023
Christopher Tate7d562ec2009-06-25 18:03:43 -07001024 // let the observer know that we're running
1025 if (mObserver != null) {
1026 try {
1027 // !!! TODO: get an actual count from the transport after
1028 // its startRestore() runs?
1029 mObserver.restoreStarting(restorePackages.size());
1030 } catch (RemoteException e) {
1031 Log.d(TAG, "Restore observer died at restoreStarting");
1032 mObserver = null;
1033 }
1034 }
1035
Dan Egnor156411d2009-06-26 13:20:02 -07001036 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -07001037 // STOPSHIP TODO: Handle the failure somehow?
1038 Log.e(TAG, "Error starting restore operation");
1039 return;
1040 }
1041
1042 String packageName = mTransport.nextRestorePackage();
1043 if (packageName == null) {
1044 // STOPSHIP TODO: Handle the failure somehow?
1045 Log.e(TAG, "Error getting first restore package");
1046 return;
1047 } else if (packageName.equals("")) {
1048 Log.i(TAG, "No restore data available");
1049 return;
1050 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1051 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1052 + "\", found only \"" + packageName + "\"");
1053 return;
1054 }
1055
1056 // Pull the Package Manager metadata from the restore set first
1057 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1058 mPackageManager, agentPackages);
1059 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1060
Christopher Tate8c032472009-07-02 14:28:47 -07001061 // Verify that the backup set includes metadata. If not, we can't do
1062 // signature/version verification etc, so we simply do not proceed with
1063 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001064 if (!pmAgent.hasMetadata()) {
Christopher Tate8c032472009-07-02 14:28:47 -07001065 Log.i(TAG, "No restore metadata available, so not restoring settings");
1066 return;
1067 }
1068
Christopher Tate7d562ec2009-06-25 18:03:43 -07001069 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001070 for (;;) {
1071 packageName = mTransport.nextRestorePackage();
1072 if (packageName == null) {
1073 // STOPSHIP TODO: Handle the failure somehow?
1074 Log.e(TAG, "Error getting next restore package");
1075 return;
1076 } else if (packageName.equals("")) {
1077 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001078 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001079
Christopher Tate7d562ec2009-06-25 18:03:43 -07001080 if (mObserver != null) {
1081 ++count;
1082 try {
1083 mObserver.onUpdate(count);
1084 } catch (RemoteException e) {
1085 Log.d(TAG, "Restore observer died in onUpdate");
1086 mObserver = null;
1087 }
1088 }
1089
Dan Egnorefe52642009-06-24 00:16:33 -07001090 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1091 if (metaInfo == null) {
1092 Log.e(TAG, "Missing metadata for " + packageName);
1093 continue;
1094 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001095
Dan Egnorefe52642009-06-24 00:16:33 -07001096 int flags = PackageManager.GET_SIGNATURES;
1097 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1098 if (metaInfo.versionCode > packageInfo.versionCode) {
1099 Log.w(TAG, "Package " + packageName
1100 + " restore version [" + metaInfo.versionCode
1101 + "] is too new for installed version ["
1102 + packageInfo.versionCode + "]");
1103 continue;
1104 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001105
Dan Egnorefe52642009-06-24 00:16:33 -07001106 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1107 Log.w(TAG, "Signature mismatch restoring " + packageName);
1108 continue;
1109 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001110
Dan Egnorefe52642009-06-24 00:16:33 -07001111 if (DEBUG) Log.v(TAG, "Package " + packageName
1112 + " restore version [" + metaInfo.versionCode
1113 + "] is compatible with installed version ["
1114 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001115
Dan Egnorefe52642009-06-24 00:16:33 -07001116 // Now perform the actual restore
1117 clearApplicationDataSynchronous(packageName);
1118 IBackupAgent agent = bindToAgentSynchronous(
1119 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001120 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -07001121 if (agent == null) {
1122 Log.w(TAG, "Can't find backup agent for " + packageName);
1123 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001124 }
1125
Dan Egnorefe52642009-06-24 00:16:33 -07001126 try {
1127 processOneRestore(packageInfo, metaInfo.versionCode, agent);
1128 } finally {
1129 // unbind even on timeout or failure, just in case
1130 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
1131 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001132 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001133
1134 // if we get this far, report success to the observer
1135 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001136 } catch (NameNotFoundException e) {
1137 // STOPSHIP TODO: Handle the failure somehow?
1138 Log.e(TAG, "Invalid paackage restoring data", e);
1139 } catch (RemoteException e) {
1140 // STOPSHIP TODO: Handle the failure somehow?
1141 Log.e(TAG, "Error restoring data", e);
1142 } finally {
1143 try {
1144 mTransport.finishRestore();
1145 } catch (RemoteException e) {
1146 Log.e(TAG, "Error finishing restore", e);
1147 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001148
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001149 Log.d(TAG, "finishing restore mObserver=" + mObserver);
1150
Christopher Tate7d562ec2009-06-25 18:03:43 -07001151 if (mObserver != null) {
1152 try {
1153 mObserver.restoreFinished(error);
1154 } catch (RemoteException e) {
1155 Log.d(TAG, "Restore observer died at restoreFinished");
1156 }
1157 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001158
1159 // done; we can finally release the wakelock
1160 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001161 }
1162 }
1163
Dan Egnorefe52642009-06-24 00:16:33 -07001164 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1165 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001166 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001167 final String packageName = app.packageName;
1168
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001169 Log.d(TAG, "processOneRestore packageName=" + packageName);
1170
Christopher Tatec7b31e32009-06-10 15:49:30 -07001171 // !!! TODO: get the dirs from the transport
1172 File backupDataName = new File(mDataDir, packageName + ".restore");
1173 backupDataName.delete();
1174 try {
1175 ParcelFileDescriptor backupData =
1176 ParcelFileDescriptor.open(backupDataName,
1177 ParcelFileDescriptor.MODE_READ_WRITE |
1178 ParcelFileDescriptor.MODE_CREATE);
1179
1180 // Run the transport's restore pass
1181 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001182 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001183 if (!mTransport.getRestoreData(backupData)) {
1184 // STOPSHIP TODO: Handle this error somehow?
1185 Log.e(TAG, "Error getting restore data for " + packageName);
1186 return;
1187 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001188 } finally {
1189 backupData.close();
1190 }
1191
1192 // Okay, we have the data. Now have the agent do the restore.
1193 File newStateName = new File(mStateDir, packageName + ".new");
1194 ParcelFileDescriptor newState =
1195 ParcelFileDescriptor.open(newStateName,
1196 ParcelFileDescriptor.MODE_READ_WRITE |
1197 ParcelFileDescriptor.MODE_CREATE);
1198
1199 backupData = ParcelFileDescriptor.open(backupDataName,
1200 ParcelFileDescriptor.MODE_READ_ONLY);
1201
Christopher Tatec7b31e32009-06-10 15:49:30 -07001202 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001203 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001204 } finally {
1205 newState.close();
1206 backupData.close();
1207 }
1208
1209 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001210 File savedStateName = new File(mStateDir, packageName);
1211 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001212 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001213 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001214 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001215 }
1216 }
1217
Christopher Tateee0e78a2009-07-02 11:17:03 -07001218 class PerformClearThread extends Thread {
1219 IBackupTransport mTransport;
1220 PackageInfo mPackage;
1221
1222 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1223 mTransport = transport;
1224 mPackage = packageInfo;
1225 }
1226
1227 @Override
1228 public void run() {
1229 try {
1230 // Clear the on-device backup state to ensure a full backup next time
1231 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1232 File stateFile = new File(stateDir, mPackage.packageName);
1233 stateFile.delete();
1234
1235 // Tell the transport to remove all the persistent storage for the app
1236 mTransport.clearBackupData(mPackage);
1237 } catch (RemoteException e) {
1238 // can't happen; the transport is local
1239 } finally {
1240 try {
1241 mTransport.finishBackup();
1242 } catch (RemoteException e) {
1243 // can't happen; the transport is local
1244 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001245
1246 // Last but not least, release the cpu
1247 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001248 }
1249 }
1250 }
1251
Christopher Tatedf01dea2009-06-09 20:45:02 -07001252
Christopher Tate487529a2009-04-29 14:03:25 -07001253 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001254
Christopher Tatea8bf8152009-04-30 11:36:21 -07001255 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001256 // Record that we need a backup pass for the caller. Since multiple callers
1257 // may share a uid, we need to note all candidates within that uid and schedule
1258 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001259
Christopher Tate63d27002009-06-16 17:16:42 -07001260 // If the caller does not hold the BACKUP permission, it can only request a
1261 // backup of its own data.
1262 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001263 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001264 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1265 targets = mBackupParticipants.get(Binder.getCallingUid());
1266 } else {
1267 // a caller with full permission can ask to back up any participating app
1268 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001269 targets = new HashSet<ApplicationInfo>();
1270 int N = mBackupParticipants.size();
1271 for (int i = 0; i < N; i++) {
1272 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1273 if (s != null) {
1274 targets.addAll(s);
1275 }
1276 }
1277 }
Christopher Tate487529a2009-04-29 14:03:25 -07001278 if (targets != null) {
1279 synchronized (mQueueLock) {
1280 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001281 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001282 // validate the caller-supplied package name against the known set of
1283 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001284 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001285 // Add the caller to the set of pending backups. If there is
1286 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001287 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001288 if (mPendingBackups.put(app, req) == null) {
1289 // Journal this request in case of crash. The put()
1290 // operation returned null when this package was not already
1291 // in the set; we want to avoid touching the disk redundantly.
1292 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001293
Christopher Tate22b60d82009-07-07 16:36:02 -07001294 if (DEBUG) {
1295 int numKeys = mPendingBackups.size();
1296 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1297 for (BackupRequest b : mPendingBackups.values()) {
1298 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1299 }
1300 }
1301 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001302 }
1303 }
Christopher Tate487529a2009-04-29 14:03:25 -07001304 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001305 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001306 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1307 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001308 }
1309 }
Christopher Tate46758122009-05-06 11:22:00 -07001310
Christopher Tatecde87f42009-06-12 12:55:53 -07001311 private void writeToJournalLocked(String str) {
1312 if (mJournalStream != null) {
1313 try {
1314 mJournalStream.writeUTF(str);
1315 } catch (IOException e) {
1316 Log.e(TAG, "Error writing to backup journal");
1317 mJournalStream = null;
1318 mJournal = null;
1319 }
1320 }
1321 }
1322
Christopher Tateee0e78a2009-07-02 11:17:03 -07001323 // Clear the given package's backup data from the current transport
1324 public void clearBackupData(String packageName) {
1325 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1326 PackageInfo info;
1327 try {
1328 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1329 } catch (NameNotFoundException e) {
1330 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1331 return;
1332 }
1333
1334 // If the caller does not hold the BACKUP permission, it can only request a
1335 // wipe of its own backed-up data.
1336 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001337 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001338 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1339 apps = mBackupParticipants.get(Binder.getCallingUid());
1340 } else {
1341 // a caller with full permission can ask to back up any participating app
1342 // !!! TODO: allow data-clear of ANY app?
1343 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1344 apps = new HashSet<ApplicationInfo>();
1345 int N = mBackupParticipants.size();
1346 for (int i = 0; i < N; i++) {
1347 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1348 if (s != null) {
1349 apps.addAll(s);
1350 }
1351 }
1352 }
1353
1354 // now find the given package in the set of candidate apps
1355 for (ApplicationInfo app : apps) {
1356 if (app.packageName.equals(packageName)) {
1357 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1358 // found it; fire off the clear request
1359 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001360 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001361 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1362 new ClearParams(getTransport(mCurrentTransport), info));
1363 mBackupHandler.sendMessage(msg);
1364 }
1365 break;
1366 }
1367 }
1368 }
1369
Christopher Tateace7f092009-06-15 18:07:25 -07001370 // Run a backup pass immediately for any applications that have declared
1371 // that they have pending updates.
1372 public void backupNow() throws RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001373 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001374
Christopher Tateace7f092009-06-15 18:07:25 -07001375 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001376 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001377 try {
1378 if (DEBUG) Log.v(TAG, "sending immediate backup broadcast");
1379 mRunBackupIntent.send();
1380 } catch (PendingIntent.CanceledException e) {
1381 // should never happen
1382 Log.e(TAG, "run-backup intent cancelled!");
1383 }
Christopher Tate46758122009-05-06 11:22:00 -07001384 }
1385 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001386
Christopher Tate8031a3d2009-07-06 16:36:05 -07001387 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001388 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1390 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001391
1392 boolean wasEnabled = mEnabled;
1393 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001394 Settings.Secure.putInt(mContext.getContentResolver(),
1395 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001396 mEnabled = enable;
1397 }
1398
Christopher Tate49401dd2009-07-01 12:34:29 -07001399 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001400 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001401 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001402 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001403 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001404 // No longer enabled, so stop running backups
1405 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001406 }
1407 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001408 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001409
Christopher Tate8031a3d2009-07-06 16:36:05 -07001410 // Mark the backup service as having been provisioned
1411 public void setBackupProvisioned(boolean available) {
1412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1413 "setBackupProvisioned");
1414
1415 boolean wasProvisioned = mProvisioned;
1416 synchronized (this) {
1417 Settings.Secure.putInt(mContext.getContentResolver(),
1418 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1419 mProvisioned = available;
1420 }
1421
1422 synchronized (mQueueLock) {
1423 if (available && !wasProvisioned && mEnabled) {
1424 // we're now good to go, so start the backup alarms
1425 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1426 } else if (!available) {
1427 // No longer enabled, so stop running backups
1428 Log.w(TAG, "Backup service no longer provisioned");
1429 mAlarmManager.cancel(mRunBackupIntent);
1430 }
1431 }
1432 }
1433
1434 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1435 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1436 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1437 BACKUP_INTERVAL, mRunBackupIntent);
1438 }
1439
Christopher Tate6ef58a12009-06-29 14:56:28 -07001440 // Report whether the backup mechanism is currently enabled
1441 public boolean isBackupEnabled() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001442 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001443 return mEnabled; // no need to synchronize just to read it
1444 }
1445
Christopher Tate91717492009-06-26 21:07:13 -07001446 // Report the name of the currently active transport
1447 public String getCurrentTransport() {
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001448 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
1449 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001450 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001451 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001452 }
1453
Christopher Tate91717492009-06-26 21:07:13 -07001454 // Report all known, available backup transports
1455 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001456 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001457
Christopher Tate91717492009-06-26 21:07:13 -07001458 String[] list = null;
1459 ArrayList<String> known = new ArrayList<String>();
1460 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1461 if (entry.getValue() != null) {
1462 known.add(entry.getKey());
1463 }
1464 }
1465
1466 if (known.size() > 0) {
1467 list = new String[known.size()];
1468 known.toArray(list);
1469 }
1470 return list;
1471 }
1472
1473 // Select which transport to use for the next backup operation. If the given
1474 // name is not one of the available transports, no action is taken and the method
1475 // returns null.
1476 public String selectBackupTransport(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001477 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001478
1479 synchronized (mTransports) {
1480 String prevTransport = null;
1481 if (mTransports.get(transport) != null) {
1482 prevTransport = mCurrentTransport;
1483 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001484 Settings.Secure.putString(mContext.getContentResolver(),
1485 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001486 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1487 + " returning " + prevTransport);
1488 } else {
1489 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1490 }
1491 return prevTransport;
1492 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001493 }
1494
1495 // Callback: a requested backup agent has been instantiated. This should only
1496 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001497 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001498 synchronized(mAgentConnectLock) {
1499 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1500 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1501 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1502 mConnectedAgent = agent;
1503 mConnecting = false;
1504 } else {
1505 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1506 + " claiming agent connected");
1507 }
1508 mAgentConnectLock.notifyAll();
1509 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001510 }
1511
1512 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1513 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001514 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001515 public void agentDisconnected(String packageName) {
1516 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001517 synchronized(mAgentConnectLock) {
1518 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1519 mConnectedAgent = null;
1520 mConnecting = false;
1521 } else {
1522 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1523 + " claiming agent disconnected");
1524 }
1525 mAgentConnectLock.notifyAll();
1526 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001527 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001528
Christopher Tate8c850b72009-06-07 19:33:20 -07001529 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001530 public IRestoreSession beginRestoreSession(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001531 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001532
1533 synchronized(this) {
1534 if (mActiveRestoreSession != null) {
1535 Log.d(TAG, "Restore session requested but one already active");
1536 return null;
1537 }
Christopher Tate91717492009-06-26 21:07:13 -07001538 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001539 }
1540 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001541 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001542
Christopher Tate9b3905c2009-06-08 15:24:01 -07001543 // ----- Restore session -----
1544
1545 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001546 private static final String TAG = "RestoreSession";
1547
Christopher Tate9b3905c2009-06-08 15:24:01 -07001548 private IBackupTransport mRestoreTransport = null;
1549 RestoreSet[] mRestoreSets = null;
1550
Christopher Tate91717492009-06-26 21:07:13 -07001551 RestoreSession(String transport) {
1552 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001553 }
1554
1555 // --- Binder interface ---
1556 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001557 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001558 "getAvailableRestoreSets");
1559
Christopher Tatef68eb502009-06-16 11:02:01 -07001560 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001561 synchronized(this) {
Christopher Tate43383042009-07-13 15:17:13 -07001562 if (mRestoreTransport == null) {
1563 Log.w(TAG, "Null transport getting restore sets");
1564 } else if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07001565 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1566 }
1567 return mRestoreSets;
1568 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001569 } catch (RuntimeException e) {
1570 Log.d(TAG, "getAvailableRestoreSets exception");
1571 e.printStackTrace();
1572 throw e;
1573 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001574 }
1575
Dan Egnor156411d2009-06-26 13:20:02 -07001576 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001577 throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001578 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001579
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001580 Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
1581
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001582 if (mRestoreSets != null) {
1583 for (int i = 0; i < mRestoreSets.length; i++) {
1584 if (token == mRestoreSets[i].token) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001585 mWakelock.acquire();
Christopher Tate7d562ec2009-06-25 18:03:43 -07001586 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001587 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001588 mBackupHandler.sendMessage(msg);
1589 return 0;
1590 }
1591 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001592 } else {
1593 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001594 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001595 return -1;
1596 }
1597
1598 public void endRestoreSession() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001599 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001600 "endRestoreSession");
1601
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001602 Log.d(TAG, "endRestoreSession");
1603
Dan Egnorefe52642009-06-24 00:16:33 -07001604 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001605 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001606 synchronized(BackupManagerService.this) {
1607 if (BackupManagerService.this.mActiveRestoreSession == this) {
1608 BackupManagerService.this.mActiveRestoreSession = null;
1609 } else {
1610 Log.e(TAG, "ending non-current restore session");
1611 }
1612 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001613 }
1614 }
1615
Christopher Tate043dadc2009-06-02 16:11:00 -07001616
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001617 @Override
1618 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1619 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001620 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
1621 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07001622 pw.println("Available transports:");
1623 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001624 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1625 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001626 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001627 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001628 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001629 for (int i=0; i<N; i++) {
1630 int uid = mBackupParticipants.keyAt(i);
1631 pw.print(" uid: ");
1632 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001633 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1634 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001635 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001636 }
1637 }
Christopher Tate73e02522009-07-15 14:18:26 -07001638 pw.println("Ever backed up: " + mEverStoredApps.size());
1639 for (String pkg : mEverStoredApps) {
1640 pw.println(" " + pkg);
1641 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001642 pw.println("Pending: " + mPendingBackups.size());
1643 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001644 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001645 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001646 }
1647 }
Christopher Tate487529a2009-04-29 14:03:25 -07001648}