blob: e47d853809bb453ec3e4f481276b4fccbfc09a76 [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 Tateb6787f22009-07-02 17:40:45 -070084 private static final String RUN_BACKUP_ACTION = "_backup_run_";
Christopher Tate487529a2009-04-29 14:03:25 -070085 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070086 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070087 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070088 private static final int MSG_RUN_CLEAR = 4;
Christopher Tatec7b31e32009-06-10 15:49:30 -070089
90 // Timeout interval for deciding that a bind or clear-data has taken too long
91 static final long TIMEOUT_INTERVAL = 10 * 1000;
92
Christopher Tate487529a2009-04-29 14:03:25 -070093 private Context mContext;
94 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -070095 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -070096 private PowerManager mPowerManager;
97 private AlarmManager mAlarmManager;
98
Christopher Tate6ef58a12009-06-29 14:56:28 -070099 private boolean mEnabled; // access to this is synchronized on 'this'
Christopher Tateb6787f22009-07-02 17:40:45 -0700100 private PowerManager.WakeLock mWakelock;
Christopher Tate487529a2009-04-29 14:03:25 -0700101 private final BackupHandler mBackupHandler = new BackupHandler();
Christopher Tateb6787f22009-07-02 17:40:45 -0700102 private PendingIntent mRunBackupIntent;
103 private BroadcastReceiver mRunBackupReceiver;
104 private IntentFilter mRunBackupFilter;
Christopher Tate487529a2009-04-29 14:03:25 -0700105 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate6ef58a12009-06-29 14:56:28 -0700106 private final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700107 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700108 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -0700109 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700110 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700111 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700112
Christopher Tate181fafa2009-05-14 11:12:14 -0700113 BackupRequest(ApplicationInfo app, boolean isFull) {
114 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700115 fullBackup = isFull;
116 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700117
118 public String toString() {
119 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
120 }
Christopher Tate46758122009-05-06 11:22:00 -0700121 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400122 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700123 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
124 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700125
126 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate6785dd82009-06-18 15:58:25 -0700127 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700128
129 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700130 private final Object mQueueLock = new Object();
131
Christopher Tate043dadc2009-06-02 16:11:00 -0700132 // The thread performing the sequence of queued backups binds to each app's agent
133 // in succession. Bind notifications are asynchronously delivered through the
134 // Activity Manager; use this lock object to signal when a requested binding has
135 // completed.
136 private final Object mAgentConnectLock = new Object();
137 private IBackupAgent mConnectedAgent;
138 private volatile boolean mConnecting;
139
Christopher Tatec7b31e32009-06-10 15:49:30 -0700140 // A similar synchronicity mechanism around clearing apps' data for restore
141 private final Object mClearDataLock = new Object();
142 private volatile boolean mClearingData;
143
Christopher Tate91717492009-06-26 21:07:13 -0700144 // Transport bookkeeping
Christopher Tate91717492009-06-26 21:07:13 -0700145 private final HashMap<String,IBackupTransport> mTransports
146 = new HashMap<String,IBackupTransport>();
147 private String mCurrentTransport;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700148 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700149 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700150
Christopher Tate7d562ec2009-06-25 18:03:43 -0700151 private class RestoreParams {
152 public IBackupTransport transport;
153 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700154 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700155
Dan Egnor156411d2009-06-26 13:20:02 -0700156 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700157 transport = _transport;
158 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700159 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700160 }
161 }
162
Christopher Tateee0e78a2009-07-02 11:17:03 -0700163 private class ClearParams {
164 public IBackupTransport transport;
165 public PackageInfo packageInfo;
166
167 ClearParams(IBackupTransport _transport, PackageInfo _info) {
168 transport = _transport;
169 packageInfo = _info;
170 }
171 }
172
Christopher Tate5cb400b2009-06-25 16:03:14 -0700173 // Where we keep our journal files and other bookkeeping
174 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700175 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700176 private File mJournalDir;
177 private File mJournal;
178 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700179
Christopher Tate487529a2009-04-29 14:03:25 -0700180 public BackupManagerService(Context context) {
181 mContext = context;
182 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700183 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700184
Christopher Tateb6787f22009-07-02 17:40:45 -0700185 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
186 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
187
Christopher Tate22b87872009-05-04 16:41:53 -0700188 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700189 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700190 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700191 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700192 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700193
Christopher Tateb6787f22009-07-02 17:40:45 -0700194 mRunBackupReceiver = new RunBackupReceiver();
195 mRunBackupFilter = new IntentFilter();
196 mRunBackupFilter.addAction(RUN_BACKUP_ACTION);
197 context.registerReceiver(mRunBackupReceiver, mRunBackupFilter);
198
199 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
200 // !!! TODO: restrict delivery to our receiver; the naive setClass() doesn't seem to work
201 //backupIntent.setClass(context, mRunBackupReceiver.getClass());
202 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
203 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
204
Christopher Tatecde87f42009-06-12 12:55:53 -0700205 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700206 mJournalDir = new File(mBaseStateDir, "pending");
207 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700208 makeJournalLocked(); // okay because no other threads are running yet
209
Christopher Tateabce4e82009-06-18 18:35:32 -0700210 // Build our mapping of uid to backup client services. This implicitly
211 // schedules a backup pass on the Package Manager metadata the first
212 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700213 synchronized (mBackupParticipants) {
214 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700215 }
216
Dan Egnor87a02bc2009-06-17 02:30:10 -0700217 // Set up our transport options and initialize the default transport
218 // TODO: Have transports register themselves somehow?
219 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700220 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700221 ComponentName localName = new ComponentName(context, LocalTransport.class);
222 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700223
Christopher Tate91717492009-06-26 21:07:13 -0700224 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700225 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
226 Settings.Secure.BACKUP_TRANSPORT);
227 if ("".equals(mCurrentTransport)) {
228 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700229 }
Christopher Tate91717492009-06-26 21:07:13 -0700230 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
231
232 // Attach to the Google backup transport. When this comes up, it will set
233 // itself as the current transport because we explicitly reset mCurrentTransport
234 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700235 Intent intent = new Intent().setComponent(new ComponentName(
236 "com.google.android.backup",
237 "com.google.android.backup.BackupTransportService"));
238 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700239
Christopher Tatecde87f42009-06-12 12:55:53 -0700240 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700241 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700242 parseLeftoverJournals();
243
Christopher Tate3799bc22009-05-06 16:13:56 -0700244 // Register for broadcasts about package install, etc., so we can
245 // update the provider list.
246 IntentFilter filter = new IntentFilter();
247 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
248 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
249 filter.addDataScheme("package");
250 mContext.registerReceiver(mBroadcastReceiver, filter);
Christopher Tate49401dd2009-07-01 12:34:29 -0700251
Christopher Tateb6787f22009-07-02 17:40:45 -0700252 // Power management
253 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
254
255 // Start the backup passes going
256 setBackupEnabled(areEnabled);
257 }
258
259 private class RunBackupReceiver extends BroadcastReceiver {
260 public void onReceive(Context context, Intent intent) {
261 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
262 if (DEBUG) Log.v(TAG, "Running a backup pass");
263
264 synchronized (mQueueLock) {
265 // acquire a wakelock and pass it to the backup thread. it will
266 // be released once backup concludes.
267 mWakelock.acquire();
268
269 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
270 mBackupHandler.sendMessage(msg);
271 }
272 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700273 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700274 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700275
Christopher Tatecde87f42009-06-12 12:55:53 -0700276 private void makeJournalLocked() {
277 try {
278 mJournal = File.createTempFile("journal", null, mJournalDir);
279 mJournalStream = new RandomAccessFile(mJournal, "rwd");
280 } catch (IOException e) {
281 Log.e(TAG, "Unable to write backup journals");
282 mJournal = null;
283 mJournalStream = null;
284 }
285 }
286
287 private void parseLeftoverJournals() {
288 if (mJournal != null) {
289 File[] allJournals = mJournalDir.listFiles();
290 for (File f : allJournals) {
291 if (f.compareTo(mJournal) != 0) {
292 // This isn't the current journal, so it must be a leftover. Read
293 // out the package names mentioned there and schedule them for
294 // backup.
295 try {
296 Log.i(TAG, "Found stale backup journal, scheduling:");
297 RandomAccessFile in = new RandomAccessFile(f, "r");
298 while (true) {
299 String packageName = in.readUTF();
300 Log.i(TAG, " + " + packageName);
301 dataChanged(packageName);
302 }
303 } catch (EOFException e) {
304 // no more data; we're done
305 } catch (Exception e) {
306 // can't read it or other error; just skip it
307 } finally {
308 // close/delete the file
309 f.delete();
310 }
311 }
312 }
313 }
314 }
315
Christopher Tate91717492009-06-26 21:07:13 -0700316 // Add a transport to our set of available backends
317 private void registerTransport(String name, IBackupTransport transport) {
318 synchronized (mTransports) {
319 mTransports.put(name, transport);
320 }
321 }
322
Christopher Tate3799bc22009-05-06 16:13:56 -0700323 // ----- Track installation/removal of packages -----
324 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
325 public void onReceive(Context context, Intent intent) {
326 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
327
328 Uri uri = intent.getData();
329 if (uri == null) {
330 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700331 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700332 String pkgName = uri.getSchemeSpecificPart();
333 if (pkgName == null) {
334 return;
335 }
336
337 String action = intent.getAction();
338 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
339 synchronized (mBackupParticipants) {
340 Bundle extras = intent.getExtras();
341 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
342 // The package was just upgraded
343 updatePackageParticipantsLocked(pkgName);
344 } else {
345 // The package was just added
346 addPackageParticipantsLocked(pkgName);
347 }
348 }
349 }
350 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
351 Bundle extras = intent.getExtras();
352 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
353 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
354 } else {
355 synchronized (mBackupParticipants) {
356 removePackageParticipantsLocked(pkgName);
357 }
358 }
359 }
360 }
361 };
362
Dan Egnor87a02bc2009-06-17 02:30:10 -0700363 // ----- Track connection to GoogleBackupTransport service -----
364 ServiceConnection mGoogleConnection = new ServiceConnection() {
365 public void onServiceConnected(ComponentName name, IBinder service) {
366 if (DEBUG) Log.v(TAG, "Connected to Google transport");
367 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700368 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700369 }
370
371 public void onServiceDisconnected(ComponentName name) {
372 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
373 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700374 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700375 }
376 };
377
Joe Onorato8ad02812009-05-13 01:41:44 -0400378 // ----- Run the actual backup process asynchronously -----
379
Christopher Tate181fafa2009-05-14 11:12:14 -0700380 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400381 public void handleMessage(Message msg) {
382
383 switch (msg.what) {
384 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700385 {
Christopher Tate91717492009-06-26 21:07:13 -0700386 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700387 if (transport == null) {
388 Log.v(TAG, "Backup requested but no transport available");
Christopher Tateb6787f22009-07-02 17:40:45 -0700389 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700390 break;
391 }
392
Joe Onorato8ad02812009-05-13 01:41:44 -0400393 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700394 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700395 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400396 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700397 // Do we have any work to do?
398 if (mPendingBackups.size() > 0) {
399 for (BackupRequest b: mPendingBackups.values()) {
400 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700401 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700402 Log.v(TAG, "clearing pending backups");
403 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700404
Christopher Tate49401dd2009-07-01 12:34:29 -0700405 // Start a new backup-queue journal file too
406 if (mJournalStream != null) {
407 try {
408 mJournalStream.close();
409 } catch (IOException e) {
410 // don't need to do anything
411 }
412 makeJournalLocked();
413 }
414
415 // At this point, we have started a new journal file, and the old
416 // file identity is being passed to the backup processing thread.
417 // When it completes successfully, that old journal file will be
418 // deleted. If we crash prior to that, the old journal is parsed
419 // at next boot and the journaled requests fulfilled.
420 (new PerformBackupThread(transport, queue, oldJournal)).start();
421 } else {
422 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700423 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700424 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400425 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700426 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700427 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700428
429 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400430 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700431
432 case MSG_RUN_RESTORE:
433 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700434 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400435 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700436 (new PerformRestoreThread(params.transport, params.observer,
437 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700438 break;
439 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700440
441 case MSG_RUN_CLEAR:
442 {
443 ClearParams params = (ClearParams)msg.obj;
444 (new PerformClearThread(params.transport, params.packageInfo)).start();
445 break;
446 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400447 }
448 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400449 }
450
Christopher Tate181fafa2009-05-14 11:12:14 -0700451 // Add the backup agents in the given package to our set of known backup participants.
452 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700453 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700454 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700455 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700456 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700457 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700458 }
459
Christopher Tate181fafa2009-05-14 11:12:14 -0700460 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700461 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700462 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700463 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
464 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700465 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
466 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700467 }
468 }
469
Dan Egnorefe52642009-06-24 00:16:33 -0700470 for (PackageInfo pkg : targetPkgs) {
471 if (packageName == null || pkg.packageName.equals(packageName)) {
472 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700473 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700474 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700475 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700476 mBackupParticipants.put(uid, set);
477 }
Dan Egnorefe52642009-06-24 00:16:33 -0700478 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700479 }
Christopher Tate487529a2009-04-29 14:03:25 -0700480 }
481 }
482
Christopher Tate6785dd82009-06-18 15:58:25 -0700483 // Remove the given package's entry from our known active set. If
484 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700485 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700486 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700487 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700488 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700489 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700490 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700491 int flags = PackageManager.GET_SIGNATURES;
492 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700493 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700494 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700495 }
496 } else {
497 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700498 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700499 }
500 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700501 }
502
Joe Onorato8ad02812009-05-13 01:41:44 -0400503 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700504 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700505 if (DEBUG) {
506 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
507 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700508 for (PackageInfo p : agents) {
509 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700510 }
511 }
Dan Egnorefe52642009-06-24 00:16:33 -0700512 for (PackageInfo pkg : agents) {
513 if (packageName == null || pkg.packageName.equals(packageName)) {
514 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700515 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700516 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700517 // Find the existing entry with the same package name, and remove it.
518 // We can't just remove(app) because the instances are different.
519 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700520 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700521 set.remove(entry);
522 break;
523 }
524 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700525 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700526 mBackupParticipants.delete(uid);
527 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700528 }
529 }
530 }
531 }
532
Christopher Tate181fafa2009-05-14 11:12:14 -0700533 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700534 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700535 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700536 int flags = PackageManager.GET_SIGNATURES;
537 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
538 int N = packages.size();
539 for (int a = N-1; a >= 0; a--) {
540 ApplicationInfo app = packages.get(a).applicationInfo;
541 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
542 || app.backupAgentName == null) {
543 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700544 }
545 }
Dan Egnorefe52642009-06-24 00:16:33 -0700546 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700547 }
Christopher Tateaa088442009-06-16 18:25:46 -0700548
Christopher Tate3799bc22009-05-06 16:13:56 -0700549 // Reset the given package's known backup participants. Unlike add/remove, the update
550 // action cannot be passed a null package name.
551 void updatePackageParticipantsLocked(String packageName) {
552 if (packageName == null) {
553 Log.e(TAG, "updatePackageParticipants called with null package name");
554 return;
555 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700556 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700557
558 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700559 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700560 removePackageParticipantsLockedInner(packageName, allApps);
561 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700562 }
563
Dan Egnor87a02bc2009-06-17 02:30:10 -0700564 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700565 private IBackupTransport getTransport(String transportName) {
566 synchronized (mTransports) {
567 IBackupTransport transport = mTransports.get(transportName);
568 if (transport == null) {
569 Log.w(TAG, "Requested unavailable transport: " + transportName);
570 }
571 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700572 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700573 }
574
Christopher Tatedf01dea2009-06-09 20:45:02 -0700575 // fire off a backup agent, blocking until it attaches or times out
576 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
577 IBackupAgent agent = null;
578 synchronized(mAgentConnectLock) {
579 mConnecting = true;
580 mConnectedAgent = null;
581 try {
582 if (mActivityManager.bindBackupAgent(app, mode)) {
583 Log.d(TAG, "awaiting agent for " + app);
584
585 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700586 // only wait 10 seconds for the clear data to happen
587 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
588 while (mConnecting && mConnectedAgent == null
589 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700590 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700591 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700592 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700593 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700594 return null;
595 }
596 }
597
598 // if we timed out with no connect, abort and move on
599 if (mConnecting == true) {
600 Log.w(TAG, "Timeout waiting for agent " + app);
601 return null;
602 }
603 agent = mConnectedAgent;
604 }
605 } catch (RemoteException e) {
606 // can't happen
607 }
608 }
609 return agent;
610 }
611
Christopher Tatec7b31e32009-06-10 15:49:30 -0700612 // clear an application's data, blocking until the operation completes or times out
613 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700614 // Don't wipe packages marked allowClearUserData=false
615 try {
616 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
617 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
618 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
619 + packageName);
620 return;
621 }
622 } catch (NameNotFoundException e) {
623 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
624 return;
625 }
626
Christopher Tatec7b31e32009-06-10 15:49:30 -0700627 ClearDataObserver observer = new ClearDataObserver();
628
629 synchronized(mClearDataLock) {
630 mClearingData = true;
631 mPackageManager.clearApplicationUserData(packageName, observer);
632
633 // only wait 10 seconds for the clear data to happen
634 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
635 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
636 try {
637 mClearDataLock.wait(5000);
638 } catch (InterruptedException e) {
639 // won't happen, but still.
640 mClearingData = false;
641 }
642 }
643 }
644 }
645
646 class ClearDataObserver extends IPackageDataObserver.Stub {
647 public void onRemoveCompleted(String packageName, boolean succeeded)
648 throws android.os.RemoteException {
649 synchronized(mClearDataLock) {
650 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700651 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700652 }
653 }
654 }
655
Christopher Tate043dadc2009-06-02 16:11:00 -0700656 // ----- Back up a set of applications via a worker thread -----
657
658 class PerformBackupThread extends Thread {
659 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700660 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700661 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700662 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700663 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700664
Christopher Tateaa088442009-06-16 18:25:46 -0700665 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700666 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700667 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700668 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700669 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700670
671 try {
672 mStateDir = new File(mBaseStateDir, transport.transportDirName());
673 } catch (RemoteException e) {
674 // can't happen; the transport is local
675 }
676 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700677 }
678
679 @Override
680 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700681 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
682
Christopher Tate79588342009-06-30 16:11:49 -0700683 // Backups run at background priority
684 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
685
Christopher Tate5cb400b2009-06-25 16:03:14 -0700686 // The package manager doesn't have a proper <application> etc, but since
687 // it's running here in the system process we can just set up its agent
688 // directly and use a synthetic BackupRequest. We always run this pass
689 // because it's cheap and this way we guarantee that we don't get out of
690 // step even if we're selecting among various transports at run time.
691 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
692 mPackageManager, allAgentPackages());
693 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
694 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
695 processOneBackup(pmRequest,
696 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
697 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700698
699 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700700 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700701
702 // Finally, tear down the transport
703 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700704 if (!mTransport.finishBackup()) {
705 // STOPSHIP TODO: handle errors
706 Log.e(TAG, "Backup failure in finishBackup()");
707 }
708 } catch (RemoteException e) {
709 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700710 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700711
712 if (!mJournal.delete()) {
713 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
714 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700715
716 // Only once we're entirely finished do we release the wakelock
717 mWakelock.release();
Christopher Tate043dadc2009-06-02 16:11:00 -0700718 }
719
720 private void doQueuedBackups(IBackupTransport transport) {
721 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700722 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700723
724 IBackupAgent agent = null;
725 int mode = (request.fullBackup)
726 ? IApplicationThread.BACKUP_MODE_FULL
727 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
728 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700729 agent = bindToAgentSynchronous(request.appInfo, mode);
730 if (agent != null) {
731 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700732 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700733
734 // unbind even on timeout, just in case
735 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700736 } catch (SecurityException ex) {
737 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700738 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700739 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700740 Log.v(TAG, "bind/backup threw");
741 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700742 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700743
Christopher Tate043dadc2009-06-02 16:11:00 -0700744 }
745 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700746
747 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
748 final String packageName = request.appInfo.packageName;
749 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
750
751 try {
752 // Look up the package info & signatures. This is first so that if it
753 // throws an exception, there's no file setup yet that would need to
754 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700755 PackageInfo packInfo;
756 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
757 // The metadata 'package' is synthetic
758 packInfo = new PackageInfo();
759 packInfo.packageName = packageName;
760 } else {
761 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700762 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700763 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700764
765 // !!! TODO: get the state file dir from the transport
766 File savedStateName = new File(mStateDir, packageName);
767 File backupDataName = new File(mDataDir, packageName + ".data");
768 File newStateName = new File(mStateDir, packageName + ".new");
769
770 // In a full backup, we pass a null ParcelFileDescriptor as
771 // the saved-state "file"
772 ParcelFileDescriptor savedState = (request.fullBackup) ? null
773 : ParcelFileDescriptor.open(savedStateName,
774 ParcelFileDescriptor.MODE_READ_ONLY |
775 ParcelFileDescriptor.MODE_CREATE);
776
777 backupDataName.delete();
778 ParcelFileDescriptor backupData =
779 ParcelFileDescriptor.open(backupDataName,
780 ParcelFileDescriptor.MODE_READ_WRITE |
781 ParcelFileDescriptor.MODE_CREATE);
782
783 newStateName.delete();
784 ParcelFileDescriptor newState =
785 ParcelFileDescriptor.open(newStateName,
786 ParcelFileDescriptor.MODE_READ_WRITE |
787 ParcelFileDescriptor.MODE_CREATE);
788
789 // Run the target's backup pass
790 boolean success = false;
791 try {
792 agent.doBackup(savedState, backupData, newState);
793 success = true;
794 } finally {
795 if (savedState != null) {
796 savedState.close();
797 }
798 backupData.close();
799 newState.close();
800 }
801
802 // Now propagate the newly-backed-up data to the transport
803 if (success) {
804 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
805 backupData =
806 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700807 if (!transport.performBackup(packInfo, backupData)) {
808 // STOPSHIP TODO: handle errors
809 Log.e(TAG, "Backup failure in performBackup()");
810 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700811
812 // !!! TODO: After successful transport, delete the now-stale data
813 // and juggle the files so that next time the new state is passed
814 //backupDataName.delete();
815 newStateName.renameTo(savedStateName);
816 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700817 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700818 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700819 }
820 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700821 }
822
Christopher Tatedf01dea2009-06-09 20:45:02 -0700823
824 // ----- Restore handling -----
825
Christopher Tateabce4e82009-06-18 18:35:32 -0700826 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700827 // Allow unsigned apps, but not signed on one device and unsigned on the other
828 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700829 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
830 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700831 if ((storedSigs == null || storedSigs.length == 0)
832 && (deviceSigs == null || deviceSigs.length == 0)) {
833 return true;
834 }
835 if (storedSigs == null || deviceSigs == null) {
836 return false;
837 }
838
Christopher Tateabce4e82009-06-18 18:35:32 -0700839 // !!! TODO: this demands that every stored signature match one
840 // that is present on device, and does not demand the converse.
841 // Is this this right policy?
842 int nStored = storedSigs.length;
843 int nDevice = deviceSigs.length;
844
845 for (int i=0; i < nStored; i++) {
846 boolean match = false;
847 for (int j=0; j < nDevice; j++) {
848 if (storedSigs[i].equals(deviceSigs[j])) {
849 match = true;
850 break;
851 }
852 }
853 if (!match) {
854 return false;
855 }
856 }
857 return true;
858 }
859
Christopher Tatedf01dea2009-06-09 20:45:02 -0700860 class PerformRestoreThread extends Thread {
861 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700862 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700863 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700864 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700865 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700866
Christopher Tate5cbbf562009-06-22 16:44:51 -0700867 class RestoreRequest {
868 public PackageInfo app;
869 public int storedAppVersion;
870
871 RestoreRequest(PackageInfo _app, int _version) {
872 app = _app;
873 storedAppVersion = _version;
874 }
875 }
876
Christopher Tate7d562ec2009-06-25 18:03:43 -0700877 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700878 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700879 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400880 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -0700881 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700882 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700883
884 try {
885 mStateDir = new File(mBaseStateDir, transport.transportDirName());
886 } catch (RemoteException e) {
887 // can't happen; the transport is local
888 }
889 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700890 }
891
892 @Override
893 public void run() {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400894 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
895 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700896 /**
897 * Restore sequence:
898 *
Dan Egnorefe52642009-06-24 00:16:33 -0700899 * 1. get the restore set description for our identity
900 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700901 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700902 * 3. for each app in the restore queue:
903 * 3.a. clear the app data
904 * 3.b. get the restore data for the app from the transport
905 * 3.c. launch the backup agent for the app
906 * 3.d. agent.doRestore() with the data from the server
907 * 3.e. unbind the agent [and kill the app?]
908 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700909 */
910
Christopher Tate7d562ec2009-06-25 18:03:43 -0700911 int error = -1; // assume error
912
Dan Egnorefe52642009-06-24 00:16:33 -0700913 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700914 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700915 RestoreSet[] images = mTransport.getAvailableRestoreSets();
916 if (images == null) {
917 // STOPSHIP TODO: Handle the failure somehow?
918 Log.e(TAG, "Error getting restore sets");
919 return;
920 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700921
Dan Egnorefe52642009-06-24 00:16:33 -0700922 if (images.length == 0) {
923 Log.i(TAG, "No restore sets available");
924 return;
925 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700926
Dan Egnorefe52642009-06-24 00:16:33 -0700927 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700928
Dan Egnorefe52642009-06-24 00:16:33 -0700929 // Get the list of all packages which have backup enabled.
930 // (Include the Package Manager metadata pseudo-package first.)
931 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
932 PackageInfo omPackage = new PackageInfo();
933 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
934 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700935
Dan Egnorefe52642009-06-24 00:16:33 -0700936 List<PackageInfo> agentPackages = allAgentPackages();
937 restorePackages.addAll(agentPackages);
938
Christopher Tate7d562ec2009-06-25 18:03:43 -0700939 // let the observer know that we're running
940 if (mObserver != null) {
941 try {
942 // !!! TODO: get an actual count from the transport after
943 // its startRestore() runs?
944 mObserver.restoreStarting(restorePackages.size());
945 } catch (RemoteException e) {
946 Log.d(TAG, "Restore observer died at restoreStarting");
947 mObserver = null;
948 }
949 }
950
Dan Egnor156411d2009-06-26 13:20:02 -0700951 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700952 // STOPSHIP TODO: Handle the failure somehow?
953 Log.e(TAG, "Error starting restore operation");
954 return;
955 }
956
957 String packageName = mTransport.nextRestorePackage();
958 if (packageName == null) {
959 // STOPSHIP TODO: Handle the failure somehow?
960 Log.e(TAG, "Error getting first restore package");
961 return;
962 } else if (packageName.equals("")) {
963 Log.i(TAG, "No restore data available");
964 return;
965 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
966 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
967 + "\", found only \"" + packageName + "\"");
968 return;
969 }
970
971 // Pull the Package Manager metadata from the restore set first
972 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
973 mPackageManager, agentPackages);
974 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
975
Christopher Tate8c032472009-07-02 14:28:47 -0700976 // Verify that the backup set includes metadata. If not, we can't do
977 // signature/version verification etc, so we simply do not proceed with
978 // the restore operation.
979 Metadata pmMeta = pmAgent.getRestoredMetadata(packageName);
980 if (pmMeta == null) {
981 Log.i(TAG, "No restore metadata available, so not restoring settings");
982 return;
983 }
984
Christopher Tate7d562ec2009-06-25 18:03:43 -0700985 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700986 for (;;) {
987 packageName = mTransport.nextRestorePackage();
988 if (packageName == null) {
989 // STOPSHIP TODO: Handle the failure somehow?
990 Log.e(TAG, "Error getting next restore package");
991 return;
992 } else if (packageName.equals("")) {
993 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700994 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700995
Christopher Tate7d562ec2009-06-25 18:03:43 -0700996 if (mObserver != null) {
997 ++count;
998 try {
999 mObserver.onUpdate(count);
1000 } catch (RemoteException e) {
1001 Log.d(TAG, "Restore observer died in onUpdate");
1002 mObserver = null;
1003 }
1004 }
1005
Dan Egnorefe52642009-06-24 00:16:33 -07001006 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1007 if (metaInfo == null) {
1008 Log.e(TAG, "Missing metadata for " + packageName);
1009 continue;
1010 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001011
Dan Egnorefe52642009-06-24 00:16:33 -07001012 int flags = PackageManager.GET_SIGNATURES;
1013 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1014 if (metaInfo.versionCode > packageInfo.versionCode) {
1015 Log.w(TAG, "Package " + packageName
1016 + " restore version [" + metaInfo.versionCode
1017 + "] is too new for installed version ["
1018 + packageInfo.versionCode + "]");
1019 continue;
1020 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001021
Dan Egnorefe52642009-06-24 00:16:33 -07001022 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1023 Log.w(TAG, "Signature mismatch restoring " + packageName);
1024 continue;
1025 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001026
Dan Egnorefe52642009-06-24 00:16:33 -07001027 if (DEBUG) Log.v(TAG, "Package " + packageName
1028 + " restore version [" + metaInfo.versionCode
1029 + "] is compatible with installed version ["
1030 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001031
Dan Egnorefe52642009-06-24 00:16:33 -07001032 // Now perform the actual restore
1033 clearApplicationDataSynchronous(packageName);
1034 IBackupAgent agent = bindToAgentSynchronous(
1035 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001036 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -07001037 if (agent == null) {
1038 Log.w(TAG, "Can't find backup agent for " + packageName);
1039 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001040 }
1041
Dan Egnorefe52642009-06-24 00:16:33 -07001042 try {
1043 processOneRestore(packageInfo, metaInfo.versionCode, agent);
1044 } finally {
1045 // unbind even on timeout or failure, just in case
1046 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
1047 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001048 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001049
1050 // if we get this far, report success to the observer
1051 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001052 } catch (NameNotFoundException e) {
1053 // STOPSHIP TODO: Handle the failure somehow?
1054 Log.e(TAG, "Invalid paackage restoring data", e);
1055 } catch (RemoteException e) {
1056 // STOPSHIP TODO: Handle the failure somehow?
1057 Log.e(TAG, "Error restoring data", e);
1058 } finally {
1059 try {
1060 mTransport.finishRestore();
1061 } catch (RemoteException e) {
1062 Log.e(TAG, "Error finishing restore", e);
1063 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001064
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001065 Log.d(TAG, "finishing restore mObserver=" + mObserver);
1066
Christopher Tate7d562ec2009-06-25 18:03:43 -07001067 if (mObserver != null) {
1068 try {
1069 mObserver.restoreFinished(error);
1070 } catch (RemoteException e) {
1071 Log.d(TAG, "Restore observer died at restoreFinished");
1072 }
1073 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001074
1075 // done; we can finally release the wakelock
1076 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001077 }
1078 }
1079
Dan Egnorefe52642009-06-24 00:16:33 -07001080 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1081 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001082 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001083 final String packageName = app.packageName;
1084
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001085 Log.d(TAG, "processOneRestore packageName=" + packageName);
1086
Christopher Tatec7b31e32009-06-10 15:49:30 -07001087 // !!! TODO: get the dirs from the transport
1088 File backupDataName = new File(mDataDir, packageName + ".restore");
1089 backupDataName.delete();
1090 try {
1091 ParcelFileDescriptor backupData =
1092 ParcelFileDescriptor.open(backupDataName,
1093 ParcelFileDescriptor.MODE_READ_WRITE |
1094 ParcelFileDescriptor.MODE_CREATE);
1095
1096 // Run the transport's restore pass
1097 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001098 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001099 if (!mTransport.getRestoreData(backupData)) {
1100 // STOPSHIP TODO: Handle this error somehow?
1101 Log.e(TAG, "Error getting restore data for " + packageName);
1102 return;
1103 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001104 } finally {
1105 backupData.close();
1106 }
1107
1108 // Okay, we have the data. Now have the agent do the restore.
1109 File newStateName = new File(mStateDir, packageName + ".new");
1110 ParcelFileDescriptor newState =
1111 ParcelFileDescriptor.open(newStateName,
1112 ParcelFileDescriptor.MODE_READ_WRITE |
1113 ParcelFileDescriptor.MODE_CREATE);
1114
1115 backupData = ParcelFileDescriptor.open(backupDataName,
1116 ParcelFileDescriptor.MODE_READ_ONLY);
1117
Christopher Tatec7b31e32009-06-10 15:49:30 -07001118 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001119 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001120 } finally {
1121 newState.close();
1122 backupData.close();
1123 }
1124
1125 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001126 File savedStateName = new File(mStateDir, packageName);
1127 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001128 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001129 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001130 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001131 }
1132 }
1133
Christopher Tateee0e78a2009-07-02 11:17:03 -07001134 class PerformClearThread extends Thread {
1135 IBackupTransport mTransport;
1136 PackageInfo mPackage;
1137
1138 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1139 mTransport = transport;
1140 mPackage = packageInfo;
1141 }
1142
1143 @Override
1144 public void run() {
1145 try {
1146 // Clear the on-device backup state to ensure a full backup next time
1147 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1148 File stateFile = new File(stateDir, mPackage.packageName);
1149 stateFile.delete();
1150
1151 // Tell the transport to remove all the persistent storage for the app
1152 mTransport.clearBackupData(mPackage);
1153 } catch (RemoteException e) {
1154 // can't happen; the transport is local
1155 } finally {
1156 try {
1157 mTransport.finishBackup();
1158 } catch (RemoteException e) {
1159 // can't happen; the transport is local
1160 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001161
1162 // Last but not least, release the cpu
1163 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001164 }
1165 }
1166 }
1167
Christopher Tatedf01dea2009-06-09 20:45:02 -07001168
Christopher Tate487529a2009-04-29 14:03:25 -07001169 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001170
Christopher Tatea8bf8152009-04-30 11:36:21 -07001171 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001172 // Record that we need a backup pass for the caller. Since multiple callers
1173 // may share a uid, we need to note all candidates within that uid and schedule
1174 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001175
1176 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001177
1178 // If the caller does not hold the BACKUP permission, it can only request a
1179 // backup of its own data.
1180 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001181 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001182 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1183 targets = mBackupParticipants.get(Binder.getCallingUid());
1184 } else {
1185 // a caller with full permission can ask to back up any participating app
1186 // !!! TODO: allow backup of ANY app?
1187 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1188 targets = new HashSet<ApplicationInfo>();
1189 int N = mBackupParticipants.size();
1190 for (int i = 0; i < N; i++) {
1191 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1192 if (s != null) {
1193 targets.addAll(s);
1194 }
1195 }
1196 }
Christopher Tate487529a2009-04-29 14:03:25 -07001197 if (targets != null) {
1198 synchronized (mQueueLock) {
1199 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001200 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001201 // validate the caller-supplied package name against the known set of
1202 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001203 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001204 // Add the caller to the set of pending backups. If there is
1205 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001206 BackupRequest req = new BackupRequest(app, false);
1207 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001208
1209 // Journal this request in case of crash
1210 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001211 }
1212 }
1213
Christopher Tate181fafa2009-05-14 11:12:14 -07001214 if (DEBUG) {
1215 int numKeys = mPendingBackups.size();
Christopher Tate6ef58a12009-06-29 14:56:28 -07001216 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate181fafa2009-05-14 11:12:14 -07001217 for (BackupRequest b : mPendingBackups.values()) {
1218 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1219 }
1220 }
Christopher Tate487529a2009-04-29 14:03:25 -07001221 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001222 } else {
1223 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001224 }
1225 }
Christopher Tate46758122009-05-06 11:22:00 -07001226
Christopher Tatecde87f42009-06-12 12:55:53 -07001227 private void writeToJournalLocked(String str) {
1228 if (mJournalStream != null) {
1229 try {
1230 mJournalStream.writeUTF(str);
1231 } catch (IOException e) {
1232 Log.e(TAG, "Error writing to backup journal");
1233 mJournalStream = null;
1234 mJournal = null;
1235 }
1236 }
1237 }
1238
Christopher Tateee0e78a2009-07-02 11:17:03 -07001239 // Clear the given package's backup data from the current transport
1240 public void clearBackupData(String packageName) {
1241 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1242 PackageInfo info;
1243 try {
1244 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1245 } catch (NameNotFoundException e) {
1246 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1247 return;
1248 }
1249
1250 // If the caller does not hold the BACKUP permission, it can only request a
1251 // wipe of its own backed-up data.
1252 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001253 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001254 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1255 apps = mBackupParticipants.get(Binder.getCallingUid());
1256 } else {
1257 // a caller with full permission can ask to back up any participating app
1258 // !!! TODO: allow data-clear of ANY app?
1259 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1260 apps = new HashSet<ApplicationInfo>();
1261 int N = mBackupParticipants.size();
1262 for (int i = 0; i < N; i++) {
1263 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1264 if (s != null) {
1265 apps.addAll(s);
1266 }
1267 }
1268 }
1269
1270 // now find the given package in the set of candidate apps
1271 for (ApplicationInfo app : apps) {
1272 if (app.packageName.equals(packageName)) {
1273 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1274 // found it; fire off the clear request
1275 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001276 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001277 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1278 new ClearParams(getTransport(mCurrentTransport), info));
1279 mBackupHandler.sendMessage(msg);
1280 }
1281 break;
1282 }
1283 }
1284 }
1285
Christopher Tateace7f092009-06-15 18:07:25 -07001286 // Run a backup pass immediately for any applications that have declared
1287 // that they have pending updates.
1288 public void backupNow() throws RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001289 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001290
Christopher Tateace7f092009-06-15 18:07:25 -07001291 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001292 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001293 try {
1294 if (DEBUG) Log.v(TAG, "sending immediate backup broadcast");
1295 mRunBackupIntent.send();
1296 } catch (PendingIntent.CanceledException e) {
1297 // should never happen
1298 Log.e(TAG, "run-backup intent cancelled!");
1299 }
Christopher Tate46758122009-05-06 11:22:00 -07001300 }
1301 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001302
Christopher Tate6ef58a12009-06-29 14:56:28 -07001303 // Enable/disable the backup transport
1304 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001305 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1306 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001307
1308 boolean wasEnabled = mEnabled;
1309 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001310 Settings.Secure.putInt(mContext.getContentResolver(),
1311 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001312 mEnabled = enable;
1313 }
1314
Christopher Tate49401dd2009-07-01 12:34:29 -07001315 synchronized (mQueueLock) {
1316 if (enable && !wasEnabled) {
1317 // if we've just been enabled, start scheduling backup passes
Christopher Tateb6787f22009-07-02 17:40:45 -07001318 long when = System.currentTimeMillis() + BACKUP_INTERVAL;
1319 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1320 BACKUP_INTERVAL, mRunBackupIntent);
Christopher Tate49401dd2009-07-01 12:34:29 -07001321 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001322 // No longer enabled, so stop running backups
1323 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001324 }
1325 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001326 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001327
1328 // Report whether the backup mechanism is currently enabled
1329 public boolean isBackupEnabled() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001330 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001331 return mEnabled; // no need to synchronize just to read it
1332 }
1333
Christopher Tate91717492009-06-26 21:07:13 -07001334 // Report the name of the currently active transport
1335 public String getCurrentTransport() {
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001336 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
1337 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001338 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001339 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001340 }
1341
Christopher Tate91717492009-06-26 21:07:13 -07001342 // Report all known, available backup transports
1343 public String[] listAllTransports() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001344 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001345
Christopher Tate91717492009-06-26 21:07:13 -07001346 String[] list = null;
1347 ArrayList<String> known = new ArrayList<String>();
1348 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1349 if (entry.getValue() != null) {
1350 known.add(entry.getKey());
1351 }
1352 }
1353
1354 if (known.size() > 0) {
1355 list = new String[known.size()];
1356 known.toArray(list);
1357 }
1358 return list;
1359 }
1360
1361 // Select which transport to use for the next backup operation. If the given
1362 // name is not one of the available transports, no action is taken and the method
1363 // returns null.
1364 public String selectBackupTransport(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001365 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001366
1367 synchronized (mTransports) {
1368 String prevTransport = null;
1369 if (mTransports.get(transport) != null) {
1370 prevTransport = mCurrentTransport;
1371 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001372 Settings.Secure.putString(mContext.getContentResolver(),
1373 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001374 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1375 + " returning " + prevTransport);
1376 } else {
1377 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1378 }
1379 return prevTransport;
1380 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001381 }
1382
1383 // Callback: a requested backup agent has been instantiated. This should only
1384 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001385 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001386 synchronized(mAgentConnectLock) {
1387 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1388 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1389 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1390 mConnectedAgent = agent;
1391 mConnecting = false;
1392 } else {
1393 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1394 + " claiming agent connected");
1395 }
1396 mAgentConnectLock.notifyAll();
1397 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001398 }
1399
1400 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1401 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001402 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001403 public void agentDisconnected(String packageName) {
1404 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001405 synchronized(mAgentConnectLock) {
1406 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1407 mConnectedAgent = null;
1408 mConnecting = false;
1409 } else {
1410 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1411 + " claiming agent disconnected");
1412 }
1413 mAgentConnectLock.notifyAll();
1414 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001415 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001416
Christopher Tate8c850b72009-06-07 19:33:20 -07001417 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001418 public IRestoreSession beginRestoreSession(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001419 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001420
1421 synchronized(this) {
1422 if (mActiveRestoreSession != null) {
1423 Log.d(TAG, "Restore session requested but one already active");
1424 return null;
1425 }
Christopher Tate91717492009-06-26 21:07:13 -07001426 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001427 }
1428 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001429 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001430
Christopher Tate9b3905c2009-06-08 15:24:01 -07001431 // ----- Restore session -----
1432
1433 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001434 private static final String TAG = "RestoreSession";
1435
Christopher Tate9b3905c2009-06-08 15:24:01 -07001436 private IBackupTransport mRestoreTransport = null;
1437 RestoreSet[] mRestoreSets = null;
1438
Christopher Tate91717492009-06-26 21:07:13 -07001439 RestoreSession(String transport) {
1440 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001441 }
1442
1443 // --- Binder interface ---
1444 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001445 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001446 "getAvailableRestoreSets");
1447
Christopher Tatef68eb502009-06-16 11:02:01 -07001448 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001449 synchronized(this) {
1450 if (mRestoreSets == null) {
1451 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1452 }
1453 return mRestoreSets;
1454 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001455 } catch (RuntimeException e) {
1456 Log.d(TAG, "getAvailableRestoreSets exception");
1457 e.printStackTrace();
1458 throw e;
1459 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001460 }
1461
Dan Egnor156411d2009-06-26 13:20:02 -07001462 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001463 throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001464 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001465
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001466 Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
1467
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001468 if (mRestoreSets != null) {
1469 for (int i = 0; i < mRestoreSets.length; i++) {
1470 if (token == mRestoreSets[i].token) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001471 mWakelock.acquire();
Christopher Tate7d562ec2009-06-25 18:03:43 -07001472 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001473 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001474 mBackupHandler.sendMessage(msg);
1475 return 0;
1476 }
1477 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001478 } else {
1479 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001480 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001481 return -1;
1482 }
1483
1484 public void endRestoreSession() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001485 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001486 "endRestoreSession");
1487
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001488 Log.d(TAG, "endRestoreSession");
1489
Dan Egnorefe52642009-06-24 00:16:33 -07001490 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001491 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001492 synchronized(BackupManagerService.this) {
1493 if (BackupManagerService.this.mActiveRestoreSession == this) {
1494 BackupManagerService.this.mActiveRestoreSession = null;
1495 } else {
1496 Log.e(TAG, "ending non-current restore session");
1497 }
1498 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001499 }
1500 }
1501
Christopher Tate043dadc2009-06-02 16:11:00 -07001502
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001503 @Override
1504 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1505 synchronized (mQueueLock) {
Christopher Tatece0bf062009-07-01 11:43:53 -07001506 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled"));
Christopher Tate91717492009-06-26 21:07:13 -07001507 pw.println("Available transports:");
1508 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001509 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1510 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001511 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001512 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001513 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001514 for (int i=0; i<N; i++) {
1515 int uid = mBackupParticipants.keyAt(i);
1516 pw.print(" uid: ");
1517 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001518 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1519 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001520 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001521 }
1522 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001523 pw.println("Pending: " + mPendingBackups.size());
1524 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001525 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001526 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001527 }
1528 }
Christopher Tate487529a2009-04-29 14:03:25 -07001529}