blob: 4b5c3df4b51fd88802e8f084b189901b89f76ac9 [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) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700319 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700320 mTransports.put(name, transport);
321 }
322 }
323
Christopher Tate3799bc22009-05-06 16:13:56 -0700324 // ----- Track installation/removal of packages -----
325 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
326 public void onReceive(Context context, Intent intent) {
327 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
328
329 Uri uri = intent.getData();
330 if (uri == null) {
331 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700332 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700333 String pkgName = uri.getSchemeSpecificPart();
334 if (pkgName == null) {
335 return;
336 }
337
338 String action = intent.getAction();
339 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
340 synchronized (mBackupParticipants) {
341 Bundle extras = intent.getExtras();
342 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
343 // The package was just upgraded
344 updatePackageParticipantsLocked(pkgName);
345 } else {
346 // The package was just added
347 addPackageParticipantsLocked(pkgName);
348 }
349 }
350 }
351 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
352 Bundle extras = intent.getExtras();
353 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
354 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
355 } else {
356 synchronized (mBackupParticipants) {
357 removePackageParticipantsLocked(pkgName);
358 }
359 }
360 }
361 }
362 };
363
Dan Egnor87a02bc2009-06-17 02:30:10 -0700364 // ----- Track connection to GoogleBackupTransport service -----
365 ServiceConnection mGoogleConnection = new ServiceConnection() {
366 public void onServiceConnected(ComponentName name, IBinder service) {
367 if (DEBUG) Log.v(TAG, "Connected to Google transport");
368 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700369 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700370 }
371
372 public void onServiceDisconnected(ComponentName name) {
373 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
374 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700375 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700376 }
377 };
378
Joe Onorato8ad02812009-05-13 01:41:44 -0400379 // ----- Run the actual backup process asynchronously -----
380
Christopher Tate181fafa2009-05-14 11:12:14 -0700381 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400382 public void handleMessage(Message msg) {
383
384 switch (msg.what) {
385 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700386 {
Christopher Tate91717492009-06-26 21:07:13 -0700387 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700388 if (transport == null) {
389 Log.v(TAG, "Backup requested but no transport available");
Christopher Tateb6787f22009-07-02 17:40:45 -0700390 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700391 break;
392 }
393
Joe Onorato8ad02812009-05-13 01:41:44 -0400394 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700395 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700396 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400397 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700398 // Do we have any work to do?
399 if (mPendingBackups.size() > 0) {
400 for (BackupRequest b: mPendingBackups.values()) {
401 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700402 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700403 Log.v(TAG, "clearing pending backups");
404 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700405
Christopher Tate49401dd2009-07-01 12:34:29 -0700406 // Start a new backup-queue journal file too
407 if (mJournalStream != null) {
408 try {
409 mJournalStream.close();
410 } catch (IOException e) {
411 // don't need to do anything
412 }
413 makeJournalLocked();
414 }
415
416 // At this point, we have started a new journal file, and the old
417 // file identity is being passed to the backup processing thread.
418 // When it completes successfully, that old journal file will be
419 // deleted. If we crash prior to that, the old journal is parsed
420 // at next boot and the journaled requests fulfilled.
421 (new PerformBackupThread(transport, queue, oldJournal)).start();
422 } else {
423 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700424 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700425 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400426 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700427 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700428 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700429
430 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400431 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700432
433 case MSG_RUN_RESTORE:
434 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700435 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400436 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700437 (new PerformRestoreThread(params.transport, params.observer,
438 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700439 break;
440 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700441
442 case MSG_RUN_CLEAR:
443 {
444 ClearParams params = (ClearParams)msg.obj;
445 (new PerformClearThread(params.transport, params.packageInfo)).start();
446 break;
447 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400448 }
449 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400450 }
451
Christopher Tate181fafa2009-05-14 11:12:14 -0700452 // Add the backup agents in the given package to our set of known backup participants.
453 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700454 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700455 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700456 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700457 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700458 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700459 }
460
Christopher Tate181fafa2009-05-14 11:12:14 -0700461 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700462 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700463 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700464 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
465 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700466 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
467 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700468 }
469 }
470
Dan Egnorefe52642009-06-24 00:16:33 -0700471 for (PackageInfo pkg : targetPkgs) {
472 if (packageName == null || pkg.packageName.equals(packageName)) {
473 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700474 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700475 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700476 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700477 mBackupParticipants.put(uid, set);
478 }
Dan Egnorefe52642009-06-24 00:16:33 -0700479 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700480 }
Christopher Tate487529a2009-04-29 14:03:25 -0700481 }
482 }
483
Christopher Tate6785dd82009-06-18 15:58:25 -0700484 // Remove the given package's entry from our known active set. If
485 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700486 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700487 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700488 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700489 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700490 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700491 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700492 int flags = PackageManager.GET_SIGNATURES;
493 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700494 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700495 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700496 }
497 } else {
498 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700499 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700500 }
501 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700502 }
503
Joe Onorato8ad02812009-05-13 01:41:44 -0400504 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700505 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700506 if (DEBUG) {
507 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
508 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700509 for (PackageInfo p : agents) {
510 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700511 }
512 }
Dan Egnorefe52642009-06-24 00:16:33 -0700513 for (PackageInfo pkg : agents) {
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 Tatecd4ff2e2009-06-05 13:57:54 -0700518 // Find the existing entry with the same package name, and remove it.
519 // We can't just remove(app) because the instances are different.
520 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700521 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700522 set.remove(entry);
523 break;
524 }
525 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700526 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700527 mBackupParticipants.delete(uid);
528 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700529 }
530 }
531 }
532 }
533
Christopher Tate181fafa2009-05-14 11:12:14 -0700534 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700535 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700536 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700537 int flags = PackageManager.GET_SIGNATURES;
538 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
539 int N = packages.size();
540 for (int a = N-1; a >= 0; a--) {
541 ApplicationInfo app = packages.get(a).applicationInfo;
542 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
543 || app.backupAgentName == null) {
544 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700545 }
546 }
Dan Egnorefe52642009-06-24 00:16:33 -0700547 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700548 }
Christopher Tateaa088442009-06-16 18:25:46 -0700549
Christopher Tate3799bc22009-05-06 16:13:56 -0700550 // Reset the given package's known backup participants. Unlike add/remove, the update
551 // action cannot be passed a null package name.
552 void updatePackageParticipantsLocked(String packageName) {
553 if (packageName == null) {
554 Log.e(TAG, "updatePackageParticipants called with null package name");
555 return;
556 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700557 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700558
559 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700560 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700561 removePackageParticipantsLockedInner(packageName, allApps);
562 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700563 }
564
Dan Egnor87a02bc2009-06-17 02:30:10 -0700565 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700566 private IBackupTransport getTransport(String transportName) {
567 synchronized (mTransports) {
568 IBackupTransport transport = mTransports.get(transportName);
569 if (transport == null) {
570 Log.w(TAG, "Requested unavailable transport: " + transportName);
571 }
572 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700573 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700574 }
575
Christopher Tatedf01dea2009-06-09 20:45:02 -0700576 // fire off a backup agent, blocking until it attaches or times out
577 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
578 IBackupAgent agent = null;
579 synchronized(mAgentConnectLock) {
580 mConnecting = true;
581 mConnectedAgent = null;
582 try {
583 if (mActivityManager.bindBackupAgent(app, mode)) {
584 Log.d(TAG, "awaiting agent for " + app);
585
586 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700587 // only wait 10 seconds for the clear data to happen
588 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
589 while (mConnecting && mConnectedAgent == null
590 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700591 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700592 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700593 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700594 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700595 return null;
596 }
597 }
598
599 // if we timed out with no connect, abort and move on
600 if (mConnecting == true) {
601 Log.w(TAG, "Timeout waiting for agent " + app);
602 return null;
603 }
604 agent = mConnectedAgent;
605 }
606 } catch (RemoteException e) {
607 // can't happen
608 }
609 }
610 return agent;
611 }
612
Christopher Tatec7b31e32009-06-10 15:49:30 -0700613 // clear an application's data, blocking until the operation completes or times out
614 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700615 // Don't wipe packages marked allowClearUserData=false
616 try {
617 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
618 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
619 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
620 + packageName);
621 return;
622 }
623 } catch (NameNotFoundException e) {
624 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
625 return;
626 }
627
Christopher Tatec7b31e32009-06-10 15:49:30 -0700628 ClearDataObserver observer = new ClearDataObserver();
629
630 synchronized(mClearDataLock) {
631 mClearingData = true;
632 mPackageManager.clearApplicationUserData(packageName, observer);
633
634 // only wait 10 seconds for the clear data to happen
635 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
636 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
637 try {
638 mClearDataLock.wait(5000);
639 } catch (InterruptedException e) {
640 // won't happen, but still.
641 mClearingData = false;
642 }
643 }
644 }
645 }
646
647 class ClearDataObserver extends IPackageDataObserver.Stub {
648 public void onRemoveCompleted(String packageName, boolean succeeded)
649 throws android.os.RemoteException {
650 synchronized(mClearDataLock) {
651 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700652 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700653 }
654 }
655 }
656
Christopher Tate043dadc2009-06-02 16:11:00 -0700657 // ----- Back up a set of applications via a worker thread -----
658
659 class PerformBackupThread extends Thread {
660 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700661 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700662 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700663 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700664 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700665
Christopher Tateaa088442009-06-16 18:25:46 -0700666 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700667 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700668 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700669 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700670 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700671
672 try {
673 mStateDir = new File(mBaseStateDir, transport.transportDirName());
674 } catch (RemoteException e) {
675 // can't happen; the transport is local
676 }
677 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700678 }
679
680 @Override
681 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700682 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
683
Christopher Tate79588342009-06-30 16:11:49 -0700684 // Backups run at background priority
685 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
686
Christopher Tate5cb400b2009-06-25 16:03:14 -0700687 // The package manager doesn't have a proper <application> etc, but since
688 // it's running here in the system process we can just set up its agent
689 // directly and use a synthetic BackupRequest. We always run this pass
690 // because it's cheap and this way we guarantee that we don't get out of
691 // step even if we're selecting among various transports at run time.
692 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
693 mPackageManager, allAgentPackages());
694 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
695 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
696 processOneBackup(pmRequest,
697 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
698 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700699
700 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700701 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700702
703 // Finally, tear down the transport
704 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700705 if (!mTransport.finishBackup()) {
706 // STOPSHIP TODO: handle errors
707 Log.e(TAG, "Backup failure in finishBackup()");
708 }
709 } catch (RemoteException e) {
710 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700711 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700712
713 if (!mJournal.delete()) {
714 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
715 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700716
717 // Only once we're entirely finished do we release the wakelock
718 mWakelock.release();
Christopher Tate043dadc2009-06-02 16:11:00 -0700719 }
720
721 private void doQueuedBackups(IBackupTransport transport) {
722 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700723 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700724
725 IBackupAgent agent = null;
726 int mode = (request.fullBackup)
727 ? IApplicationThread.BACKUP_MODE_FULL
728 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
729 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700730 agent = bindToAgentSynchronous(request.appInfo, mode);
731 if (agent != null) {
732 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700733 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700734
735 // unbind even on timeout, just in case
736 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700737 } catch (SecurityException ex) {
738 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700739 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700740 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700741 Log.v(TAG, "bind/backup threw");
742 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700743 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700744
Christopher Tate043dadc2009-06-02 16:11:00 -0700745 }
746 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700747
748 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
749 final String packageName = request.appInfo.packageName;
750 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
751
752 try {
753 // Look up the package info & signatures. This is first so that if it
754 // throws an exception, there's no file setup yet that would need to
755 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700756 PackageInfo packInfo;
757 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
758 // The metadata 'package' is synthetic
759 packInfo = new PackageInfo();
760 packInfo.packageName = packageName;
761 } else {
762 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700763 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700764 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700765
766 // !!! TODO: get the state file dir from the transport
767 File savedStateName = new File(mStateDir, packageName);
768 File backupDataName = new File(mDataDir, packageName + ".data");
769 File newStateName = new File(mStateDir, packageName + ".new");
770
771 // In a full backup, we pass a null ParcelFileDescriptor as
772 // the saved-state "file"
773 ParcelFileDescriptor savedState = (request.fullBackup) ? null
774 : ParcelFileDescriptor.open(savedStateName,
775 ParcelFileDescriptor.MODE_READ_ONLY |
776 ParcelFileDescriptor.MODE_CREATE);
777
778 backupDataName.delete();
779 ParcelFileDescriptor backupData =
780 ParcelFileDescriptor.open(backupDataName,
781 ParcelFileDescriptor.MODE_READ_WRITE |
782 ParcelFileDescriptor.MODE_CREATE);
783
784 newStateName.delete();
785 ParcelFileDescriptor newState =
786 ParcelFileDescriptor.open(newStateName,
787 ParcelFileDescriptor.MODE_READ_WRITE |
788 ParcelFileDescriptor.MODE_CREATE);
789
790 // Run the target's backup pass
791 boolean success = false;
792 try {
793 agent.doBackup(savedState, backupData, newState);
794 success = true;
795 } finally {
796 if (savedState != null) {
797 savedState.close();
798 }
799 backupData.close();
800 newState.close();
801 }
802
803 // Now propagate the newly-backed-up data to the transport
804 if (success) {
805 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
806 backupData =
807 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700808 if (!transport.performBackup(packInfo, backupData)) {
809 // STOPSHIP TODO: handle errors
810 Log.e(TAG, "Backup failure in performBackup()");
811 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700812
813 // !!! TODO: After successful transport, delete the now-stale data
814 // and juggle the files so that next time the new state is passed
815 //backupDataName.delete();
816 newStateName.renameTo(savedStateName);
817 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700818 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700819 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700820 }
821 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700822 }
823
Christopher Tatedf01dea2009-06-09 20:45:02 -0700824
825 // ----- Restore handling -----
826
Christopher Tateabce4e82009-06-18 18:35:32 -0700827 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700828 // Allow unsigned apps, but not signed on one device and unsigned on the other
829 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700830 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
831 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700832 if ((storedSigs == null || storedSigs.length == 0)
833 && (deviceSigs == null || deviceSigs.length == 0)) {
834 return true;
835 }
836 if (storedSigs == null || deviceSigs == null) {
837 return false;
838 }
839
Christopher Tateabce4e82009-06-18 18:35:32 -0700840 // !!! TODO: this demands that every stored signature match one
841 // that is present on device, and does not demand the converse.
842 // Is this this right policy?
843 int nStored = storedSigs.length;
844 int nDevice = deviceSigs.length;
845
846 for (int i=0; i < nStored; i++) {
847 boolean match = false;
848 for (int j=0; j < nDevice; j++) {
849 if (storedSigs[i].equals(deviceSigs[j])) {
850 match = true;
851 break;
852 }
853 }
854 if (!match) {
855 return false;
856 }
857 }
858 return true;
859 }
860
Christopher Tatedf01dea2009-06-09 20:45:02 -0700861 class PerformRestoreThread extends Thread {
862 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700863 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700864 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700865 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700866 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700867
Christopher Tate5cbbf562009-06-22 16:44:51 -0700868 class RestoreRequest {
869 public PackageInfo app;
870 public int storedAppVersion;
871
872 RestoreRequest(PackageInfo _app, int _version) {
873 app = _app;
874 storedAppVersion = _version;
875 }
876 }
877
Christopher Tate7d562ec2009-06-25 18:03:43 -0700878 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700879 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700880 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400881 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -0700882 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700883 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700884
885 try {
886 mStateDir = new File(mBaseStateDir, transport.transportDirName());
887 } catch (RemoteException e) {
888 // can't happen; the transport is local
889 }
890 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700891 }
892
893 @Override
894 public void run() {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400895 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
896 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700897 /**
898 * Restore sequence:
899 *
Dan Egnorefe52642009-06-24 00:16:33 -0700900 * 1. get the restore set description for our identity
901 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700902 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700903 * 3. for each app in the restore queue:
904 * 3.a. clear the app data
905 * 3.b. get the restore data for the app from the transport
906 * 3.c. launch the backup agent for the app
907 * 3.d. agent.doRestore() with the data from the server
908 * 3.e. unbind the agent [and kill the app?]
909 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700910 */
911
Christopher Tate7d562ec2009-06-25 18:03:43 -0700912 int error = -1; // assume error
913
Dan Egnorefe52642009-06-24 00:16:33 -0700914 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700915 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700916 RestoreSet[] images = mTransport.getAvailableRestoreSets();
917 if (images == null) {
918 // STOPSHIP TODO: Handle the failure somehow?
919 Log.e(TAG, "Error getting restore sets");
920 return;
921 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700922
Dan Egnorefe52642009-06-24 00:16:33 -0700923 if (images.length == 0) {
924 Log.i(TAG, "No restore sets available");
925 return;
926 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700927
Dan Egnorefe52642009-06-24 00:16:33 -0700928 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700929
Dan Egnorefe52642009-06-24 00:16:33 -0700930 // Get the list of all packages which have backup enabled.
931 // (Include the Package Manager metadata pseudo-package first.)
932 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
933 PackageInfo omPackage = new PackageInfo();
934 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
935 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700936
Dan Egnorefe52642009-06-24 00:16:33 -0700937 List<PackageInfo> agentPackages = allAgentPackages();
938 restorePackages.addAll(agentPackages);
939
Christopher Tate7d562ec2009-06-25 18:03:43 -0700940 // let the observer know that we're running
941 if (mObserver != null) {
942 try {
943 // !!! TODO: get an actual count from the transport after
944 // its startRestore() runs?
945 mObserver.restoreStarting(restorePackages.size());
946 } catch (RemoteException e) {
947 Log.d(TAG, "Restore observer died at restoreStarting");
948 mObserver = null;
949 }
950 }
951
Dan Egnor156411d2009-06-26 13:20:02 -0700952 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700953 // STOPSHIP TODO: Handle the failure somehow?
954 Log.e(TAG, "Error starting restore operation");
955 return;
956 }
957
958 String packageName = mTransport.nextRestorePackage();
959 if (packageName == null) {
960 // STOPSHIP TODO: Handle the failure somehow?
961 Log.e(TAG, "Error getting first restore package");
962 return;
963 } else if (packageName.equals("")) {
964 Log.i(TAG, "No restore data available");
965 return;
966 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
967 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
968 + "\", found only \"" + packageName + "\"");
969 return;
970 }
971
972 // Pull the Package Manager metadata from the restore set first
973 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
974 mPackageManager, agentPackages);
975 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
976
Christopher Tate8c032472009-07-02 14:28:47 -0700977 // Verify that the backup set includes metadata. If not, we can't do
978 // signature/version verification etc, so we simply do not proceed with
979 // the restore operation.
980 Metadata pmMeta = pmAgent.getRestoredMetadata(packageName);
981 if (pmMeta == null) {
982 Log.i(TAG, "No restore metadata available, so not restoring settings");
983 return;
984 }
985
Christopher Tate7d562ec2009-06-25 18:03:43 -0700986 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700987 for (;;) {
988 packageName = mTransport.nextRestorePackage();
989 if (packageName == null) {
990 // STOPSHIP TODO: Handle the failure somehow?
991 Log.e(TAG, "Error getting next restore package");
992 return;
993 } else if (packageName.equals("")) {
994 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700995 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700996
Christopher Tate7d562ec2009-06-25 18:03:43 -0700997 if (mObserver != null) {
998 ++count;
999 try {
1000 mObserver.onUpdate(count);
1001 } catch (RemoteException e) {
1002 Log.d(TAG, "Restore observer died in onUpdate");
1003 mObserver = null;
1004 }
1005 }
1006
Dan Egnorefe52642009-06-24 00:16:33 -07001007 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1008 if (metaInfo == null) {
1009 Log.e(TAG, "Missing metadata for " + packageName);
1010 continue;
1011 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001012
Dan Egnorefe52642009-06-24 00:16:33 -07001013 int flags = PackageManager.GET_SIGNATURES;
1014 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1015 if (metaInfo.versionCode > packageInfo.versionCode) {
1016 Log.w(TAG, "Package " + packageName
1017 + " restore version [" + metaInfo.versionCode
1018 + "] is too new for installed version ["
1019 + packageInfo.versionCode + "]");
1020 continue;
1021 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001022
Dan Egnorefe52642009-06-24 00:16:33 -07001023 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1024 Log.w(TAG, "Signature mismatch restoring " + packageName);
1025 continue;
1026 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001027
Dan Egnorefe52642009-06-24 00:16:33 -07001028 if (DEBUG) Log.v(TAG, "Package " + packageName
1029 + " restore version [" + metaInfo.versionCode
1030 + "] is compatible with installed version ["
1031 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001032
Dan Egnorefe52642009-06-24 00:16:33 -07001033 // Now perform the actual restore
1034 clearApplicationDataSynchronous(packageName);
1035 IBackupAgent agent = bindToAgentSynchronous(
1036 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001037 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -07001038 if (agent == null) {
1039 Log.w(TAG, "Can't find backup agent for " + packageName);
1040 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001041 }
1042
Dan Egnorefe52642009-06-24 00:16:33 -07001043 try {
1044 processOneRestore(packageInfo, metaInfo.versionCode, agent);
1045 } finally {
1046 // unbind even on timeout or failure, just in case
1047 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
1048 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001049 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001050
1051 // if we get this far, report success to the observer
1052 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001053 } catch (NameNotFoundException e) {
1054 // STOPSHIP TODO: Handle the failure somehow?
1055 Log.e(TAG, "Invalid paackage restoring data", e);
1056 } catch (RemoteException e) {
1057 // STOPSHIP TODO: Handle the failure somehow?
1058 Log.e(TAG, "Error restoring data", e);
1059 } finally {
1060 try {
1061 mTransport.finishRestore();
1062 } catch (RemoteException e) {
1063 Log.e(TAG, "Error finishing restore", e);
1064 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001065
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001066 Log.d(TAG, "finishing restore mObserver=" + mObserver);
1067
Christopher Tate7d562ec2009-06-25 18:03:43 -07001068 if (mObserver != null) {
1069 try {
1070 mObserver.restoreFinished(error);
1071 } catch (RemoteException e) {
1072 Log.d(TAG, "Restore observer died at restoreFinished");
1073 }
1074 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001075
1076 // done; we can finally release the wakelock
1077 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001078 }
1079 }
1080
Dan Egnorefe52642009-06-24 00:16:33 -07001081 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1082 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001083 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001084 final String packageName = app.packageName;
1085
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001086 Log.d(TAG, "processOneRestore packageName=" + packageName);
1087
Christopher Tatec7b31e32009-06-10 15:49:30 -07001088 // !!! TODO: get the dirs from the transport
1089 File backupDataName = new File(mDataDir, packageName + ".restore");
1090 backupDataName.delete();
1091 try {
1092 ParcelFileDescriptor backupData =
1093 ParcelFileDescriptor.open(backupDataName,
1094 ParcelFileDescriptor.MODE_READ_WRITE |
1095 ParcelFileDescriptor.MODE_CREATE);
1096
1097 // Run the transport's restore pass
1098 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001099 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001100 if (!mTransport.getRestoreData(backupData)) {
1101 // STOPSHIP TODO: Handle this error somehow?
1102 Log.e(TAG, "Error getting restore data for " + packageName);
1103 return;
1104 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001105 } finally {
1106 backupData.close();
1107 }
1108
1109 // Okay, we have the data. Now have the agent do the restore.
1110 File newStateName = new File(mStateDir, packageName + ".new");
1111 ParcelFileDescriptor newState =
1112 ParcelFileDescriptor.open(newStateName,
1113 ParcelFileDescriptor.MODE_READ_WRITE |
1114 ParcelFileDescriptor.MODE_CREATE);
1115
1116 backupData = ParcelFileDescriptor.open(backupDataName,
1117 ParcelFileDescriptor.MODE_READ_ONLY);
1118
Christopher Tatec7b31e32009-06-10 15:49:30 -07001119 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001120 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001121 } finally {
1122 newState.close();
1123 backupData.close();
1124 }
1125
1126 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001127 File savedStateName = new File(mStateDir, packageName);
1128 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001129 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001130 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001131 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001132 }
1133 }
1134
Christopher Tateee0e78a2009-07-02 11:17:03 -07001135 class PerformClearThread extends Thread {
1136 IBackupTransport mTransport;
1137 PackageInfo mPackage;
1138
1139 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1140 mTransport = transport;
1141 mPackage = packageInfo;
1142 }
1143
1144 @Override
1145 public void run() {
1146 try {
1147 // Clear the on-device backup state to ensure a full backup next time
1148 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1149 File stateFile = new File(stateDir, mPackage.packageName);
1150 stateFile.delete();
1151
1152 // Tell the transport to remove all the persistent storage for the app
1153 mTransport.clearBackupData(mPackage);
1154 } catch (RemoteException e) {
1155 // can't happen; the transport is local
1156 } finally {
1157 try {
1158 mTransport.finishBackup();
1159 } catch (RemoteException e) {
1160 // can't happen; the transport is local
1161 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001162
1163 // Last but not least, release the cpu
1164 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001165 }
1166 }
1167 }
1168
Christopher Tatedf01dea2009-06-09 20:45:02 -07001169
Christopher Tate487529a2009-04-29 14:03:25 -07001170 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001171
Christopher Tatea8bf8152009-04-30 11:36:21 -07001172 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001173 // Record that we need a backup pass for the caller. Since multiple callers
1174 // may share a uid, we need to note all candidates within that uid and schedule
1175 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001176
1177 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001178
1179 // If the caller does not hold the BACKUP permission, it can only request a
1180 // backup of its own data.
1181 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001182 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001183 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1184 targets = mBackupParticipants.get(Binder.getCallingUid());
1185 } else {
1186 // a caller with full permission can ask to back up any participating app
1187 // !!! TODO: allow backup of ANY app?
1188 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1189 targets = new HashSet<ApplicationInfo>();
1190 int N = mBackupParticipants.size();
1191 for (int i = 0; i < N; i++) {
1192 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1193 if (s != null) {
1194 targets.addAll(s);
1195 }
1196 }
1197 }
Christopher Tate487529a2009-04-29 14:03:25 -07001198 if (targets != null) {
1199 synchronized (mQueueLock) {
1200 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001201 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001202 // validate the caller-supplied package name against the known set of
1203 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001204 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001205 // Add the caller to the set of pending backups. If there is
1206 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001207 BackupRequest req = new BackupRequest(app, false);
1208 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001209
1210 // Journal this request in case of crash
1211 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001212 }
1213 }
1214
Christopher Tate181fafa2009-05-14 11:12:14 -07001215 if (DEBUG) {
1216 int numKeys = mPendingBackups.size();
Christopher Tate6ef58a12009-06-29 14:56:28 -07001217 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate181fafa2009-05-14 11:12:14 -07001218 for (BackupRequest b : mPendingBackups.values()) {
1219 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1220 }
1221 }
Christopher Tate487529a2009-04-29 14:03:25 -07001222 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001223 } else {
1224 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001225 }
1226 }
Christopher Tate46758122009-05-06 11:22:00 -07001227
Christopher Tatecde87f42009-06-12 12:55:53 -07001228 private void writeToJournalLocked(String str) {
1229 if (mJournalStream != null) {
1230 try {
1231 mJournalStream.writeUTF(str);
1232 } catch (IOException e) {
1233 Log.e(TAG, "Error writing to backup journal");
1234 mJournalStream = null;
1235 mJournal = null;
1236 }
1237 }
1238 }
1239
Christopher Tateee0e78a2009-07-02 11:17:03 -07001240 // Clear the given package's backup data from the current transport
1241 public void clearBackupData(String packageName) {
1242 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1243 PackageInfo info;
1244 try {
1245 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1246 } catch (NameNotFoundException e) {
1247 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1248 return;
1249 }
1250
1251 // If the caller does not hold the BACKUP permission, it can only request a
1252 // wipe of its own backed-up data.
1253 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001254 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001255 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1256 apps = mBackupParticipants.get(Binder.getCallingUid());
1257 } else {
1258 // a caller with full permission can ask to back up any participating app
1259 // !!! TODO: allow data-clear of ANY app?
1260 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1261 apps = new HashSet<ApplicationInfo>();
1262 int N = mBackupParticipants.size();
1263 for (int i = 0; i < N; i++) {
1264 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1265 if (s != null) {
1266 apps.addAll(s);
1267 }
1268 }
1269 }
1270
1271 // now find the given package in the set of candidate apps
1272 for (ApplicationInfo app : apps) {
1273 if (app.packageName.equals(packageName)) {
1274 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1275 // found it; fire off the clear request
1276 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001277 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001278 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1279 new ClearParams(getTransport(mCurrentTransport), info));
1280 mBackupHandler.sendMessage(msg);
1281 }
1282 break;
1283 }
1284 }
1285 }
1286
Christopher Tateace7f092009-06-15 18:07:25 -07001287 // Run a backup pass immediately for any applications that have declared
1288 // that they have pending updates.
1289 public void backupNow() throws RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001290 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001291
Christopher Tateace7f092009-06-15 18:07:25 -07001292 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001293 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001294 try {
1295 if (DEBUG) Log.v(TAG, "sending immediate backup broadcast");
1296 mRunBackupIntent.send();
1297 } catch (PendingIntent.CanceledException e) {
1298 // should never happen
1299 Log.e(TAG, "run-backup intent cancelled!");
1300 }
Christopher Tate46758122009-05-06 11:22:00 -07001301 }
1302 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001303
Christopher Tate6ef58a12009-06-29 14:56:28 -07001304 // Enable/disable the backup transport
1305 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001306 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1307 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001308
1309 boolean wasEnabled = mEnabled;
1310 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001311 Settings.Secure.putInt(mContext.getContentResolver(),
1312 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001313 mEnabled = enable;
1314 }
1315
Christopher Tate49401dd2009-07-01 12:34:29 -07001316 synchronized (mQueueLock) {
1317 if (enable && !wasEnabled) {
1318 // if we've just been enabled, start scheduling backup passes
Christopher Tateb6787f22009-07-02 17:40:45 -07001319 long when = System.currentTimeMillis() + BACKUP_INTERVAL;
1320 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1321 BACKUP_INTERVAL, mRunBackupIntent);
Christopher Tate49401dd2009-07-01 12:34:29 -07001322 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001323 // No longer enabled, so stop running backups
1324 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001325 }
1326 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001327 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001328
1329 // Report whether the backup mechanism is currently enabled
1330 public boolean isBackupEnabled() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001331 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001332 return mEnabled; // no need to synchronize just to read it
1333 }
1334
Christopher Tate91717492009-06-26 21:07:13 -07001335 // Report the name of the currently active transport
1336 public String getCurrentTransport() {
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001337 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
1338 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001339 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001340 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001341 }
1342
Christopher Tate91717492009-06-26 21:07:13 -07001343 // Report all known, available backup transports
1344 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001345 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001346
Christopher Tate91717492009-06-26 21:07:13 -07001347 String[] list = null;
1348 ArrayList<String> known = new ArrayList<String>();
1349 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1350 if (entry.getValue() != null) {
1351 known.add(entry.getKey());
1352 }
1353 }
1354
1355 if (known.size() > 0) {
1356 list = new String[known.size()];
1357 known.toArray(list);
1358 }
1359 return list;
1360 }
1361
1362 // Select which transport to use for the next backup operation. If the given
1363 // name is not one of the available transports, no action is taken and the method
1364 // returns null.
1365 public String selectBackupTransport(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001366 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001367
1368 synchronized (mTransports) {
1369 String prevTransport = null;
1370 if (mTransports.get(transport) != null) {
1371 prevTransport = mCurrentTransport;
1372 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001373 Settings.Secure.putString(mContext.getContentResolver(),
1374 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001375 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1376 + " returning " + prevTransport);
1377 } else {
1378 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1379 }
1380 return prevTransport;
1381 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001382 }
1383
1384 // Callback: a requested backup agent has been instantiated. This should only
1385 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001386 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001387 synchronized(mAgentConnectLock) {
1388 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1389 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1390 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1391 mConnectedAgent = agent;
1392 mConnecting = false;
1393 } else {
1394 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1395 + " claiming agent connected");
1396 }
1397 mAgentConnectLock.notifyAll();
1398 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001399 }
1400
1401 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1402 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001403 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001404 public void agentDisconnected(String packageName) {
1405 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001406 synchronized(mAgentConnectLock) {
1407 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1408 mConnectedAgent = null;
1409 mConnecting = false;
1410 } else {
1411 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1412 + " claiming agent disconnected");
1413 }
1414 mAgentConnectLock.notifyAll();
1415 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001416 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001417
Christopher Tate8c850b72009-06-07 19:33:20 -07001418 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001419 public IRestoreSession beginRestoreSession(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001420 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001421
1422 synchronized(this) {
1423 if (mActiveRestoreSession != null) {
1424 Log.d(TAG, "Restore session requested but one already active");
1425 return null;
1426 }
Christopher Tate91717492009-06-26 21:07:13 -07001427 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001428 }
1429 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001430 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001431
Christopher Tate9b3905c2009-06-08 15:24:01 -07001432 // ----- Restore session -----
1433
1434 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001435 private static final String TAG = "RestoreSession";
1436
Christopher Tate9b3905c2009-06-08 15:24:01 -07001437 private IBackupTransport mRestoreTransport = null;
1438 RestoreSet[] mRestoreSets = null;
1439
Christopher Tate91717492009-06-26 21:07:13 -07001440 RestoreSession(String transport) {
1441 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001442 }
1443
1444 // --- Binder interface ---
1445 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001446 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001447 "getAvailableRestoreSets");
1448
Christopher Tatef68eb502009-06-16 11:02:01 -07001449 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001450 synchronized(this) {
1451 if (mRestoreSets == null) {
1452 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1453 }
1454 return mRestoreSets;
1455 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001456 } catch (RuntimeException e) {
1457 Log.d(TAG, "getAvailableRestoreSets exception");
1458 e.printStackTrace();
1459 throw e;
1460 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001461 }
1462
Dan Egnor156411d2009-06-26 13:20:02 -07001463 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001464 throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001465 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001466
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001467 Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
1468
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001469 if (mRestoreSets != null) {
1470 for (int i = 0; i < mRestoreSets.length; i++) {
1471 if (token == mRestoreSets[i].token) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001472 mWakelock.acquire();
Christopher Tate7d562ec2009-06-25 18:03:43 -07001473 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001474 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001475 mBackupHandler.sendMessage(msg);
1476 return 0;
1477 }
1478 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001479 } else {
1480 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001481 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001482 return -1;
1483 }
1484
1485 public void endRestoreSession() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001486 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001487 "endRestoreSession");
1488
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001489 Log.d(TAG, "endRestoreSession");
1490
Dan Egnorefe52642009-06-24 00:16:33 -07001491 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001492 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001493 synchronized(BackupManagerService.this) {
1494 if (BackupManagerService.this.mActiveRestoreSession == this) {
1495 BackupManagerService.this.mActiveRestoreSession = null;
1496 } else {
1497 Log.e(TAG, "ending non-current restore session");
1498 }
1499 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001500 }
1501 }
1502
Christopher Tate043dadc2009-06-02 16:11:00 -07001503
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001504 @Override
1505 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1506 synchronized (mQueueLock) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001507 long oldId = Binder.clearCallingIdentity();
1508
Christopher Tatece0bf062009-07-01 11:43:53 -07001509 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled"));
Christopher Tate91717492009-06-26 21:07:13 -07001510 pw.println("Available transports:");
1511 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001512 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1513 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001514 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001515 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001516 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001517 for (int i=0; i<N; i++) {
1518 int uid = mBackupParticipants.keyAt(i);
1519 pw.print(" uid: ");
1520 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001521 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1522 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001523 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001524 }
1525 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001526 pw.println("Pending: " + mPendingBackups.size());
1527 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001528 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001529 }
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001530
1531 Binder.restoreCallingIdentity(oldId);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001532 }
1533 }
Christopher Tate487529a2009-04-29 14:03:25 -07001534}