blob: 80697a1795e7829dc06a8788fc7c70af5c24ed6b [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070021import android.app.IActivityManager;
22import android.app.IApplicationThread;
23import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070024import android.app.PendingIntent;
Christopher Tate3799bc22009-05-06 16:13:56 -070025import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070026import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070027import android.content.Context;
28import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070029import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070030import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070031import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070032import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070033import android.content.pm.PackageInfo;
Christopher Tate043dadc2009-06-02 16:11:00 -070034import android.content.pm.PackageManager.NameNotFoundException;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070036import android.content.pm.Signature;
Christopher Tate3799bc22009-05-06 16:13:56 -070037import android.net.Uri;
Christopher Tatece0bf062009-07-01 11:43:53 -070038import android.provider.Settings;
Christopher Tate487529a2009-04-29 14:03:25 -070039import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070040import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070041import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070042import android.os.Handler;
43import android.os.IBinder;
44import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070045import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070046import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070047import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070048import android.os.RemoteException;
49import android.util.Log;
50import android.util.SparseArray;
51
52import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070053import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070054import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070055import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070056
Christopher Tate9bbc21a2009-06-10 20:23:25 -070057import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070058import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070059
Christopher Tate6785dd82009-06-18 15:58:25 -070060import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070061import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070062
Christopher Tatecde87f42009-06-12 12:55:53 -070063import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070064import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070065import java.io.FileDescriptor;
Christopher Tatec7b31e32009-06-10 15:49:30 -070066import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070067import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070068import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070069import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040070import java.util.ArrayList;
71import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070072import java.util.HashSet;
73import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070074import java.util.Map;
Christopher Tate487529a2009-04-29 14:03:25 -070075
76class BackupManagerService extends IBackupManager.Stub {
77 private static final String TAG = "BackupManagerService";
78 private static final boolean DEBUG = true;
Christopher Tateaa088442009-06-16 18:25:46 -070079
Christopher Tate49401dd2009-07-01 12:34:29 -070080 // How often we perform a backup pass. Privileged external callers can
81 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070082 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070083
Christopher Tate8031a3d2009-07-06 16:36:05 -070084 // The amount of time between the initial provisioning of the device and
85 // the first backup pass.
86 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
87
Christopher Tateb6787f22009-07-02 17:40:45 -070088 private static final String RUN_BACKUP_ACTION = "_backup_run_";
Christopher Tate487529a2009-04-29 14:03:25 -070089 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070090 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070091 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070092 private static final int MSG_RUN_CLEAR = 4;
Christopher Tatec7b31e32009-06-10 15:49:30 -070093
94 // Timeout interval for deciding that a bind or clear-data has taken too long
95 static final long TIMEOUT_INTERVAL = 10 * 1000;
96
Christopher Tate487529a2009-04-29 14:03:25 -070097 private Context mContext;
98 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -070099 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700100 private PowerManager mPowerManager;
101 private AlarmManager mAlarmManager;
102
Christopher Tate6ef58a12009-06-29 14:56:28 -0700103 private boolean mEnabled; // access to this is synchronized on 'this'
Christopher Tate8031a3d2009-07-06 16:36:05 -0700104 private boolean mProvisioned;
Christopher Tateb6787f22009-07-02 17:40:45 -0700105 private PowerManager.WakeLock mWakelock;
Christopher Tate487529a2009-04-29 14:03:25 -0700106 private final BackupHandler mBackupHandler = new BackupHandler();
Christopher Tateb6787f22009-07-02 17:40:45 -0700107 private PendingIntent mRunBackupIntent;
108 private BroadcastReceiver mRunBackupReceiver;
109 private IntentFilter mRunBackupFilter;
Christopher Tate487529a2009-04-29 14:03:25 -0700110 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate6ef58a12009-06-29 14:56:28 -0700111 private final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700112 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700113 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -0700114 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700115 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700116 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700117
Christopher Tate181fafa2009-05-14 11:12:14 -0700118 BackupRequest(ApplicationInfo app, boolean isFull) {
119 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700120 fullBackup = isFull;
121 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700122
123 public String toString() {
124 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
125 }
Christopher Tate46758122009-05-06 11:22:00 -0700126 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400127 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -0700128 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
129 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700130
131 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate6785dd82009-06-18 15:58:25 -0700132 private static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700133
134 // locking around the pending-backup management
Christopher Tate487529a2009-04-29 14:03:25 -0700135 private final Object mQueueLock = new Object();
136
Christopher Tate043dadc2009-06-02 16:11:00 -0700137 // The thread performing the sequence of queued backups binds to each app's agent
138 // in succession. Bind notifications are asynchronously delivered through the
139 // Activity Manager; use this lock object to signal when a requested binding has
140 // completed.
141 private final Object mAgentConnectLock = new Object();
142 private IBackupAgent mConnectedAgent;
143 private volatile boolean mConnecting;
144
Christopher Tatec7b31e32009-06-10 15:49:30 -0700145 // A similar synchronicity mechanism around clearing apps' data for restore
146 private final Object mClearDataLock = new Object();
147 private volatile boolean mClearingData;
148
Christopher Tate91717492009-06-26 21:07:13 -0700149 // Transport bookkeeping
Christopher Tate91717492009-06-26 21:07:13 -0700150 private final HashMap<String,IBackupTransport> mTransports
151 = new HashMap<String,IBackupTransport>();
152 private String mCurrentTransport;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700153 private IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tatef68eb502009-06-16 11:02:01 -0700154 private RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700155
Christopher Tate7d562ec2009-06-25 18:03:43 -0700156 private class RestoreParams {
157 public IBackupTransport transport;
158 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700159 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700160
Dan Egnor156411d2009-06-26 13:20:02 -0700161 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700162 transport = _transport;
163 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700164 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700165 }
166 }
167
Christopher Tateee0e78a2009-07-02 11:17:03 -0700168 private class ClearParams {
169 public IBackupTransport transport;
170 public PackageInfo packageInfo;
171
172 ClearParams(IBackupTransport _transport, PackageInfo _info) {
173 transport = _transport;
174 packageInfo = _info;
175 }
176 }
177
Christopher Tate5cb400b2009-06-25 16:03:14 -0700178 // Where we keep our journal files and other bookkeeping
179 private File mBaseStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700180 private File mDataDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700181 private File mJournalDir;
182 private File mJournal;
183 private RandomAccessFile mJournalStream;
Christopher Tateaa088442009-06-16 18:25:46 -0700184
Christopher Tate487529a2009-04-29 14:03:25 -0700185 public BackupManagerService(Context context) {
186 mContext = context;
187 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700188 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700189
Christopher Tateb6787f22009-07-02 17:40:45 -0700190 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
191 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
192
Christopher Tate22b87872009-05-04 16:41:53 -0700193 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700194 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700195 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700196 // !!! TODO: mProvisioned needs to default to 0, not 1.
197 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
198 Settings.Secure.BACKUP_PROVISIONED, 1) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700199 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700200 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700201
Christopher Tateb6787f22009-07-02 17:40:45 -0700202 mRunBackupReceiver = new RunBackupReceiver();
203 mRunBackupFilter = new IntentFilter();
204 mRunBackupFilter.addAction(RUN_BACKUP_ACTION);
205 context.registerReceiver(mRunBackupReceiver, mRunBackupFilter);
206
207 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
208 // !!! TODO: restrict delivery to our receiver; the naive setClass() doesn't seem to work
209 //backupIntent.setClass(context, mRunBackupReceiver.getClass());
210 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
211 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
212
Christopher Tatecde87f42009-06-12 12:55:53 -0700213 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700214 mJournalDir = new File(mBaseStateDir, "pending");
215 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Christopher Tatecde87f42009-06-12 12:55:53 -0700216 makeJournalLocked(); // okay because no other threads are running yet
217
Christopher Tateabce4e82009-06-18 18:35:32 -0700218 // Build our mapping of uid to backup client services. This implicitly
219 // schedules a backup pass on the Package Manager metadata the first
220 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700221 synchronized (mBackupParticipants) {
222 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700223 }
224
Dan Egnor87a02bc2009-06-17 02:30:10 -0700225 // Set up our transport options and initialize the default transport
226 // TODO: Have transports register themselves somehow?
227 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700228 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700229 ComponentName localName = new ComponentName(context, LocalTransport.class);
230 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700231
Christopher Tate91717492009-06-26 21:07:13 -0700232 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700233 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
234 Settings.Secure.BACKUP_TRANSPORT);
235 if ("".equals(mCurrentTransport)) {
236 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700237 }
Christopher Tate91717492009-06-26 21:07:13 -0700238 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
239
240 // Attach to the Google backup transport. When this comes up, it will set
241 // itself as the current transport because we explicitly reset mCurrentTransport
242 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700243 Intent intent = new Intent().setComponent(new ComponentName(
244 "com.google.android.backup",
245 "com.google.android.backup.BackupTransportService"));
246 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700247
Christopher Tatecde87f42009-06-12 12:55:53 -0700248 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700249 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700250 parseLeftoverJournals();
251
Christopher Tate3799bc22009-05-06 16:13:56 -0700252 // Register for broadcasts about package install, etc., so we can
253 // update the provider list.
254 IntentFilter filter = new IntentFilter();
255 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
256 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
257 filter.addDataScheme("package");
258 mContext.registerReceiver(mBroadcastReceiver, filter);
Christopher Tate49401dd2009-07-01 12:34:29 -0700259
Christopher Tateb6787f22009-07-02 17:40:45 -0700260 // Power management
261 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
262
263 // Start the backup passes going
264 setBackupEnabled(areEnabled);
265 }
266
267 private class RunBackupReceiver extends BroadcastReceiver {
268 public void onReceive(Context context, Intent intent) {
269 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
270 if (DEBUG) Log.v(TAG, "Running a backup pass");
271
272 synchronized (mQueueLock) {
273 // acquire a wakelock and pass it to the backup thread. it will
274 // be released once backup concludes.
275 mWakelock.acquire();
276
277 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
278 mBackupHandler.sendMessage(msg);
279 }
280 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700281 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700282 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700283
Christopher Tatecde87f42009-06-12 12:55:53 -0700284 private void makeJournalLocked() {
285 try {
286 mJournal = File.createTempFile("journal", null, mJournalDir);
287 mJournalStream = new RandomAccessFile(mJournal, "rwd");
288 } catch (IOException e) {
289 Log.e(TAG, "Unable to write backup journals");
290 mJournal = null;
291 mJournalStream = null;
292 }
293 }
294
295 private void parseLeftoverJournals() {
296 if (mJournal != null) {
297 File[] allJournals = mJournalDir.listFiles();
298 for (File f : allJournals) {
299 if (f.compareTo(mJournal) != 0) {
300 // This isn't the current journal, so it must be a leftover. Read
301 // out the package names mentioned there and schedule them for
302 // backup.
303 try {
304 Log.i(TAG, "Found stale backup journal, scheduling:");
305 RandomAccessFile in = new RandomAccessFile(f, "r");
306 while (true) {
307 String packageName = in.readUTF();
308 Log.i(TAG, " + " + packageName);
309 dataChanged(packageName);
310 }
311 } catch (EOFException e) {
312 // no more data; we're done
313 } catch (Exception e) {
314 // can't read it or other error; just skip it
315 } finally {
316 // close/delete the file
317 f.delete();
318 }
319 }
320 }
321 }
322 }
323
Christopher Tate91717492009-06-26 21:07:13 -0700324 // Add a transport to our set of available backends
325 private void registerTransport(String name, IBackupTransport transport) {
326 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700327 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700328 mTransports.put(name, transport);
329 }
330 }
331
Christopher Tate3799bc22009-05-06 16:13:56 -0700332 // ----- Track installation/removal of packages -----
333 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
334 public void onReceive(Context context, Intent intent) {
335 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
336
337 Uri uri = intent.getData();
338 if (uri == null) {
339 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700340 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700341 String pkgName = uri.getSchemeSpecificPart();
342 if (pkgName == null) {
343 return;
344 }
345
346 String action = intent.getAction();
347 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
348 synchronized (mBackupParticipants) {
349 Bundle extras = intent.getExtras();
350 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
351 // The package was just upgraded
352 updatePackageParticipantsLocked(pkgName);
353 } else {
354 // The package was just added
355 addPackageParticipantsLocked(pkgName);
356 }
357 }
358 }
359 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
360 Bundle extras = intent.getExtras();
361 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
362 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
363 } else {
364 synchronized (mBackupParticipants) {
365 removePackageParticipantsLocked(pkgName);
366 }
367 }
368 }
369 }
370 };
371
Dan Egnor87a02bc2009-06-17 02:30:10 -0700372 // ----- Track connection to GoogleBackupTransport service -----
373 ServiceConnection mGoogleConnection = new ServiceConnection() {
374 public void onServiceConnected(ComponentName name, IBinder service) {
375 if (DEBUG) Log.v(TAG, "Connected to Google transport");
376 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700377 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700378 }
379
380 public void onServiceDisconnected(ComponentName name) {
381 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
382 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700383 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700384 }
385 };
386
Joe Onorato8ad02812009-05-13 01:41:44 -0400387 // ----- Run the actual backup process asynchronously -----
388
Christopher Tate181fafa2009-05-14 11:12:14 -0700389 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400390 public void handleMessage(Message msg) {
391
392 switch (msg.what) {
393 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700394 {
Christopher Tate91717492009-06-26 21:07:13 -0700395 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700396 if (transport == null) {
397 Log.v(TAG, "Backup requested but no transport available");
Christopher Tateb6787f22009-07-02 17:40:45 -0700398 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700399 break;
400 }
401
Joe Onorato8ad02812009-05-13 01:41:44 -0400402 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700403 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatecde87f42009-06-12 12:55:53 -0700404 File oldJournal = mJournal;
Joe Onorato8ad02812009-05-13 01:41:44 -0400405 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700406 // Do we have any work to do?
407 if (mPendingBackups.size() > 0) {
408 for (BackupRequest b: mPendingBackups.values()) {
409 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700410 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700411 Log.v(TAG, "clearing pending backups");
412 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700413
Christopher Tate49401dd2009-07-01 12:34:29 -0700414 // Start a new backup-queue journal file too
415 if (mJournalStream != null) {
416 try {
417 mJournalStream.close();
418 } catch (IOException e) {
419 // don't need to do anything
420 }
421 makeJournalLocked();
422 }
423
424 // At this point, we have started a new journal file, and the old
425 // file identity is being passed to the backup processing thread.
426 // When it completes successfully, that old journal file will be
427 // deleted. If we crash prior to that, the old journal is parsed
428 // at next boot and the journaled requests fulfilled.
429 (new PerformBackupThread(transport, queue, oldJournal)).start();
430 } else {
431 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tateb6787f22009-07-02 17:40:45 -0700432 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700433 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400434 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700435 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700436 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700437
438 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400439 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700440
441 case MSG_RUN_RESTORE:
442 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700443 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400444 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700445 (new PerformRestoreThread(params.transport, params.observer,
446 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700447 break;
448 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700449
450 case MSG_RUN_CLEAR:
451 {
452 ClearParams params = (ClearParams)msg.obj;
453 (new PerformClearThread(params.transport, params.packageInfo)).start();
454 break;
455 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400456 }
457 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400458 }
459
Christopher Tate181fafa2009-05-14 11:12:14 -0700460 // Add the backup agents in the given package to our set of known backup participants.
461 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700462 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700463 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700464 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700465 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700466 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700467 }
468
Christopher Tate181fafa2009-05-14 11:12:14 -0700469 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700470 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700471 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700472 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
473 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700474 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
475 + " uid=" + p.applicationInfo.uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700476 }
477 }
478
Dan Egnorefe52642009-06-24 00:16:33 -0700479 for (PackageInfo pkg : targetPkgs) {
480 if (packageName == null || pkg.packageName.equals(packageName)) {
481 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700482 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700483 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700484 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700485 mBackupParticipants.put(uid, set);
486 }
Dan Egnorefe52642009-06-24 00:16:33 -0700487 set.add(pkg.applicationInfo);
Christopher Tate3799bc22009-05-06 16:13:56 -0700488 }
Christopher Tate487529a2009-04-29 14:03:25 -0700489 }
490 }
491
Christopher Tate6785dd82009-06-18 15:58:25 -0700492 // Remove the given package's entry from our known active set. If
493 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700494 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700495 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700496 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700497 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700498 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700499 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700500 int flags = PackageManager.GET_SIGNATURES;
501 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700502 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700503 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700504 }
505 } else {
506 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700507 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700508 }
509 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700510 }
511
Joe Onorato8ad02812009-05-13 01:41:44 -0400512 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700513 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700514 if (DEBUG) {
515 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
516 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700517 for (PackageInfo p : agents) {
518 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700519 }
520 }
Dan Egnorefe52642009-06-24 00:16:33 -0700521 for (PackageInfo pkg : agents) {
522 if (packageName == null || pkg.packageName.equals(packageName)) {
523 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700524 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700525 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700526 // Find the existing entry with the same package name, and remove it.
527 // We can't just remove(app) because the instances are different.
528 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700529 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700530 set.remove(entry);
531 break;
532 }
533 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700534 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700535 mBackupParticipants.delete(uid);
536 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700537 }
538 }
539 }
540 }
541
Christopher Tate181fafa2009-05-14 11:12:14 -0700542 // Returns the set of all applications that define an android:backupAgent attribute
Dan Egnorefe52642009-06-24 00:16:33 -0700543 private List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700544 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700545 int flags = PackageManager.GET_SIGNATURES;
546 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
547 int N = packages.size();
548 for (int a = N-1; a >= 0; a--) {
549 ApplicationInfo app = packages.get(a).applicationInfo;
550 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
551 || app.backupAgentName == null) {
552 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700553 }
554 }
Dan Egnorefe52642009-06-24 00:16:33 -0700555 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700556 }
Christopher Tateaa088442009-06-16 18:25:46 -0700557
Christopher Tate3799bc22009-05-06 16:13:56 -0700558 // Reset the given package's known backup participants. Unlike add/remove, the update
559 // action cannot be passed a null package name.
560 void updatePackageParticipantsLocked(String packageName) {
561 if (packageName == null) {
562 Log.e(TAG, "updatePackageParticipants called with null package name");
563 return;
564 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700565 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700566
567 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700568 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700569 removePackageParticipantsLockedInner(packageName, allApps);
570 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700571 }
572
Dan Egnor87a02bc2009-06-17 02:30:10 -0700573 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700574 private IBackupTransport getTransport(String transportName) {
575 synchronized (mTransports) {
576 IBackupTransport transport = mTransports.get(transportName);
577 if (transport == null) {
578 Log.w(TAG, "Requested unavailable transport: " + transportName);
579 }
580 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700581 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700582 }
583
Christopher Tatedf01dea2009-06-09 20:45:02 -0700584 // fire off a backup agent, blocking until it attaches or times out
585 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
586 IBackupAgent agent = null;
587 synchronized(mAgentConnectLock) {
588 mConnecting = true;
589 mConnectedAgent = null;
590 try {
591 if (mActivityManager.bindBackupAgent(app, mode)) {
592 Log.d(TAG, "awaiting agent for " + app);
593
594 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700595 // only wait 10 seconds for the clear data to happen
596 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
597 while (mConnecting && mConnectedAgent == null
598 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700599 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700600 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700601 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700602 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700603 return null;
604 }
605 }
606
607 // if we timed out with no connect, abort and move on
608 if (mConnecting == true) {
609 Log.w(TAG, "Timeout waiting for agent " + app);
610 return null;
611 }
612 agent = mConnectedAgent;
613 }
614 } catch (RemoteException e) {
615 // can't happen
616 }
617 }
618 return agent;
619 }
620
Christopher Tatec7b31e32009-06-10 15:49:30 -0700621 // clear an application's data, blocking until the operation completes or times out
622 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700623 // Don't wipe packages marked allowClearUserData=false
624 try {
625 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
626 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
627 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
628 + packageName);
629 return;
630 }
631 } catch (NameNotFoundException e) {
632 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
633 return;
634 }
635
Christopher Tatec7b31e32009-06-10 15:49:30 -0700636 ClearDataObserver observer = new ClearDataObserver();
637
638 synchronized(mClearDataLock) {
639 mClearingData = true;
640 mPackageManager.clearApplicationUserData(packageName, observer);
641
642 // only wait 10 seconds for the clear data to happen
643 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
644 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
645 try {
646 mClearDataLock.wait(5000);
647 } catch (InterruptedException e) {
648 // won't happen, but still.
649 mClearingData = false;
650 }
651 }
652 }
653 }
654
655 class ClearDataObserver extends IPackageDataObserver.Stub {
656 public void onRemoveCompleted(String packageName, boolean succeeded)
657 throws android.os.RemoteException {
658 synchronized(mClearDataLock) {
659 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700660 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700661 }
662 }
663 }
664
Christopher Tate043dadc2009-06-02 16:11:00 -0700665 // ----- Back up a set of applications via a worker thread -----
666
667 class PerformBackupThread extends Thread {
668 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700669 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700670 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700671 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700672 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700673
Christopher Tateaa088442009-06-16 18:25:46 -0700674 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700675 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700676 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700677 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700678 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700679
680 try {
681 mStateDir = new File(mBaseStateDir, transport.transportDirName());
682 } catch (RemoteException e) {
683 // can't happen; the transport is local
684 }
685 mStateDir.mkdirs();
Christopher Tate043dadc2009-06-02 16:11:00 -0700686 }
687
688 @Override
689 public void run() {
Christopher Tate043dadc2009-06-02 16:11:00 -0700690 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
691
Christopher Tate79588342009-06-30 16:11:49 -0700692 // Backups run at background priority
693 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
694
Christopher Tate5cb400b2009-06-25 16:03:14 -0700695 // The package manager doesn't have a proper <application> etc, but since
696 // it's running here in the system process we can just set up its agent
697 // directly and use a synthetic BackupRequest. We always run this pass
698 // because it's cheap and this way we guarantee that we don't get out of
699 // step even if we're selecting among various transports at run time.
700 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
701 mPackageManager, allAgentPackages());
702 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
703 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
704 processOneBackup(pmRequest,
705 IBackupAgent.Stub.asInterface(pmAgent.onBind()),
706 mTransport);
Christopher Tate6785dd82009-06-18 15:58:25 -0700707
708 // Now run all the backups in our queue
Christopher Tateaa088442009-06-16 18:25:46 -0700709 doQueuedBackups(mTransport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700710
711 // Finally, tear down the transport
712 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700713 if (!mTransport.finishBackup()) {
714 // STOPSHIP TODO: handle errors
715 Log.e(TAG, "Backup failure in finishBackup()");
716 }
717 } catch (RemoteException e) {
718 Log.e(TAG, "Error in finishBackup()", e);
Christopher Tate043dadc2009-06-02 16:11:00 -0700719 }
Christopher Tatecde87f42009-06-12 12:55:53 -0700720
721 if (!mJournal.delete()) {
722 Log.e(TAG, "Unable to remove backup journal file " + mJournal.getAbsolutePath());
723 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700724
725 // Only once we're entirely finished do we release the wakelock
726 mWakelock.release();
Christopher Tate043dadc2009-06-02 16:11:00 -0700727 }
728
729 private void doQueuedBackups(IBackupTransport transport) {
730 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700731 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -0700732
733 IBackupAgent agent = null;
734 int mode = (request.fullBackup)
735 ? IApplicationThread.BACKUP_MODE_FULL
736 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
737 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700738 agent = bindToAgentSynchronous(request.appInfo, mode);
739 if (agent != null) {
740 processOneBackup(request, agent, transport);
Christopher Tate043dadc2009-06-02 16:11:00 -0700741 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700742
743 // unbind even on timeout, just in case
744 mActivityManager.unbindBackupAgent(request.appInfo);
Christopher Tate043dadc2009-06-02 16:11:00 -0700745 } catch (SecurityException ex) {
746 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -0700747 Log.d(TAG, "error in bind/backup", ex);
Christopher Tate043dadc2009-06-02 16:11:00 -0700748 } catch (RemoteException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700749 Log.v(TAG, "bind/backup threw");
750 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -0700751 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700752
Christopher Tate043dadc2009-06-02 16:11:00 -0700753 }
754 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700755
756 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
757 final String packageName = request.appInfo.packageName;
758 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
759
760 try {
761 // Look up the package info & signatures. This is first so that if it
762 // throws an exception, there's no file setup yet that would need to
763 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -0700764 PackageInfo packInfo;
765 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
766 // The metadata 'package' is synthetic
767 packInfo = new PackageInfo();
768 packInfo.packageName = packageName;
769 } else {
770 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -0700771 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -0700772 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700773
774 // !!! TODO: get the state file dir from the transport
775 File savedStateName = new File(mStateDir, packageName);
776 File backupDataName = new File(mDataDir, packageName + ".data");
777 File newStateName = new File(mStateDir, packageName + ".new");
778
779 // In a full backup, we pass a null ParcelFileDescriptor as
780 // the saved-state "file"
781 ParcelFileDescriptor savedState = (request.fullBackup) ? null
782 : ParcelFileDescriptor.open(savedStateName,
783 ParcelFileDescriptor.MODE_READ_ONLY |
784 ParcelFileDescriptor.MODE_CREATE);
785
786 backupDataName.delete();
787 ParcelFileDescriptor backupData =
788 ParcelFileDescriptor.open(backupDataName,
789 ParcelFileDescriptor.MODE_READ_WRITE |
790 ParcelFileDescriptor.MODE_CREATE);
791
792 newStateName.delete();
793 ParcelFileDescriptor newState =
794 ParcelFileDescriptor.open(newStateName,
795 ParcelFileDescriptor.MODE_READ_WRITE |
796 ParcelFileDescriptor.MODE_CREATE);
797
798 // Run the target's backup pass
799 boolean success = false;
800 try {
801 agent.doBackup(savedState, backupData, newState);
802 success = true;
803 } finally {
804 if (savedState != null) {
805 savedState.close();
806 }
807 backupData.close();
808 newState.close();
809 }
810
811 // Now propagate the newly-backed-up data to the transport
812 if (success) {
813 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
814 backupData =
815 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Dan Egnorefe52642009-06-24 00:16:33 -0700816 if (!transport.performBackup(packInfo, backupData)) {
817 // STOPSHIP TODO: handle errors
818 Log.e(TAG, "Backup failure in performBackup()");
819 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700820
821 // !!! TODO: After successful transport, delete the now-stale data
822 // and juggle the files so that next time the new state is passed
823 //backupDataName.delete();
824 newStateName.renameTo(savedStateName);
825 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700826 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700827 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700828 }
829 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700830 }
831
Christopher Tatedf01dea2009-06-09 20:45:02 -0700832
833 // ----- Restore handling -----
834
Christopher Tateabce4e82009-06-18 18:35:32 -0700835 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700836 // Allow unsigned apps, but not signed on one device and unsigned on the other
837 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700838 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
839 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700840 if ((storedSigs == null || storedSigs.length == 0)
841 && (deviceSigs == null || deviceSigs.length == 0)) {
842 return true;
843 }
844 if (storedSigs == null || deviceSigs == null) {
845 return false;
846 }
847
Christopher Tateabce4e82009-06-18 18:35:32 -0700848 // !!! TODO: this demands that every stored signature match one
849 // that is present on device, and does not demand the converse.
850 // Is this this right policy?
851 int nStored = storedSigs.length;
852 int nDevice = deviceSigs.length;
853
854 for (int i=0; i < nStored; i++) {
855 boolean match = false;
856 for (int j=0; j < nDevice; j++) {
857 if (storedSigs[i].equals(deviceSigs[j])) {
858 match = true;
859 break;
860 }
861 }
862 if (!match) {
863 return false;
864 }
865 }
866 return true;
867 }
868
Christopher Tatedf01dea2009-06-09 20:45:02 -0700869 class PerformRestoreThread extends Thread {
870 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700871 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700872 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700873 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700874 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700875
Christopher Tate5cbbf562009-06-22 16:44:51 -0700876 class RestoreRequest {
877 public PackageInfo app;
878 public int storedAppVersion;
879
880 RestoreRequest(PackageInfo _app, int _version) {
881 app = _app;
882 storedAppVersion = _version;
883 }
884 }
885
Christopher Tate7d562ec2009-06-25 18:03:43 -0700886 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700887 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700888 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400889 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -0700890 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700891 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700892
893 try {
894 mStateDir = new File(mBaseStateDir, transport.transportDirName());
895 } catch (RemoteException e) {
896 // can't happen; the transport is local
897 }
898 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700899 }
900
901 @Override
902 public void run() {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400903 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
904 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700905 /**
906 * Restore sequence:
907 *
Dan Egnorefe52642009-06-24 00:16:33 -0700908 * 1. get the restore set description for our identity
909 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700910 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700911 * 3. for each app in the restore queue:
912 * 3.a. clear the app data
913 * 3.b. get the restore data for the app from the transport
914 * 3.c. launch the backup agent for the app
915 * 3.d. agent.doRestore() with the data from the server
916 * 3.e. unbind the agent [and kill the app?]
917 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700918 */
919
Christopher Tate7d562ec2009-06-25 18:03:43 -0700920 int error = -1; // assume error
921
Dan Egnorefe52642009-06-24 00:16:33 -0700922 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700923 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700924 RestoreSet[] images = mTransport.getAvailableRestoreSets();
925 if (images == null) {
926 // STOPSHIP TODO: Handle the failure somehow?
927 Log.e(TAG, "Error getting restore sets");
928 return;
929 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700930
Dan Egnorefe52642009-06-24 00:16:33 -0700931 if (images.length == 0) {
932 Log.i(TAG, "No restore sets available");
933 return;
934 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700935
Dan Egnorefe52642009-06-24 00:16:33 -0700936 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700937
Dan Egnorefe52642009-06-24 00:16:33 -0700938 // Get the list of all packages which have backup enabled.
939 // (Include the Package Manager metadata pseudo-package first.)
940 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
941 PackageInfo omPackage = new PackageInfo();
942 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
943 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700944
Dan Egnorefe52642009-06-24 00:16:33 -0700945 List<PackageInfo> agentPackages = allAgentPackages();
946 restorePackages.addAll(agentPackages);
947
Christopher Tate7d562ec2009-06-25 18:03:43 -0700948 // let the observer know that we're running
949 if (mObserver != null) {
950 try {
951 // !!! TODO: get an actual count from the transport after
952 // its startRestore() runs?
953 mObserver.restoreStarting(restorePackages.size());
954 } catch (RemoteException e) {
955 Log.d(TAG, "Restore observer died at restoreStarting");
956 mObserver = null;
957 }
958 }
959
Dan Egnor156411d2009-06-26 13:20:02 -0700960 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700961 // STOPSHIP TODO: Handle the failure somehow?
962 Log.e(TAG, "Error starting restore operation");
963 return;
964 }
965
966 String packageName = mTransport.nextRestorePackage();
967 if (packageName == null) {
968 // STOPSHIP TODO: Handle the failure somehow?
969 Log.e(TAG, "Error getting first restore package");
970 return;
971 } else if (packageName.equals("")) {
972 Log.i(TAG, "No restore data available");
973 return;
974 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
975 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
976 + "\", found only \"" + packageName + "\"");
977 return;
978 }
979
980 // Pull the Package Manager metadata from the restore set first
981 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
982 mPackageManager, agentPackages);
983 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
984
Christopher Tate8c032472009-07-02 14:28:47 -0700985 // Verify that the backup set includes metadata. If not, we can't do
986 // signature/version verification etc, so we simply do not proceed with
987 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -0700988 if (!pmAgent.hasMetadata()) {
Christopher Tate8c032472009-07-02 14:28:47 -0700989 Log.i(TAG, "No restore metadata available, so not restoring settings");
990 return;
991 }
992
Christopher Tate7d562ec2009-06-25 18:03:43 -0700993 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -0700994 for (;;) {
995 packageName = mTransport.nextRestorePackage();
996 if (packageName == null) {
997 // STOPSHIP TODO: Handle the failure somehow?
998 Log.e(TAG, "Error getting next restore package");
999 return;
1000 } else if (packageName.equals("")) {
1001 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001002 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001003
Christopher Tate7d562ec2009-06-25 18:03:43 -07001004 if (mObserver != null) {
1005 ++count;
1006 try {
1007 mObserver.onUpdate(count);
1008 } catch (RemoteException e) {
1009 Log.d(TAG, "Restore observer died in onUpdate");
1010 mObserver = null;
1011 }
1012 }
1013
Dan Egnorefe52642009-06-24 00:16:33 -07001014 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1015 if (metaInfo == null) {
1016 Log.e(TAG, "Missing metadata for " + packageName);
1017 continue;
1018 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001019
Dan Egnorefe52642009-06-24 00:16:33 -07001020 int flags = PackageManager.GET_SIGNATURES;
1021 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1022 if (metaInfo.versionCode > packageInfo.versionCode) {
1023 Log.w(TAG, "Package " + packageName
1024 + " restore version [" + metaInfo.versionCode
1025 + "] is too new for installed version ["
1026 + packageInfo.versionCode + "]");
1027 continue;
1028 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001029
Dan Egnorefe52642009-06-24 00:16:33 -07001030 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1031 Log.w(TAG, "Signature mismatch restoring " + packageName);
1032 continue;
1033 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001034
Dan Egnorefe52642009-06-24 00:16:33 -07001035 if (DEBUG) Log.v(TAG, "Package " + packageName
1036 + " restore version [" + metaInfo.versionCode
1037 + "] is compatible with installed version ["
1038 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001039
Dan Egnorefe52642009-06-24 00:16:33 -07001040 // Now perform the actual restore
1041 clearApplicationDataSynchronous(packageName);
1042 IBackupAgent agent = bindToAgentSynchronous(
1043 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001044 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -07001045 if (agent == null) {
1046 Log.w(TAG, "Can't find backup agent for " + packageName);
1047 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001048 }
1049
Dan Egnorefe52642009-06-24 00:16:33 -07001050 try {
1051 processOneRestore(packageInfo, metaInfo.versionCode, agent);
1052 } finally {
1053 // unbind even on timeout or failure, just in case
1054 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
1055 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001056 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001057
1058 // if we get this far, report success to the observer
1059 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001060 } catch (NameNotFoundException e) {
1061 // STOPSHIP TODO: Handle the failure somehow?
1062 Log.e(TAG, "Invalid paackage restoring data", e);
1063 } catch (RemoteException e) {
1064 // STOPSHIP TODO: Handle the failure somehow?
1065 Log.e(TAG, "Error restoring data", e);
1066 } finally {
1067 try {
1068 mTransport.finishRestore();
1069 } catch (RemoteException e) {
1070 Log.e(TAG, "Error finishing restore", e);
1071 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001072
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001073 Log.d(TAG, "finishing restore mObserver=" + mObserver);
1074
Christopher Tate7d562ec2009-06-25 18:03:43 -07001075 if (mObserver != null) {
1076 try {
1077 mObserver.restoreFinished(error);
1078 } catch (RemoteException e) {
1079 Log.d(TAG, "Restore observer died at restoreFinished");
1080 }
1081 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001082
1083 // done; we can finally release the wakelock
1084 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001085 }
1086 }
1087
Dan Egnorefe52642009-06-24 00:16:33 -07001088 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1089 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001090 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001091 final String packageName = app.packageName;
1092
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001093 Log.d(TAG, "processOneRestore packageName=" + packageName);
1094
Christopher Tatec7b31e32009-06-10 15:49:30 -07001095 // !!! TODO: get the dirs from the transport
1096 File backupDataName = new File(mDataDir, packageName + ".restore");
1097 backupDataName.delete();
1098 try {
1099 ParcelFileDescriptor backupData =
1100 ParcelFileDescriptor.open(backupDataName,
1101 ParcelFileDescriptor.MODE_READ_WRITE |
1102 ParcelFileDescriptor.MODE_CREATE);
1103
1104 // Run the transport's restore pass
1105 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001106 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001107 if (!mTransport.getRestoreData(backupData)) {
1108 // STOPSHIP TODO: Handle this error somehow?
1109 Log.e(TAG, "Error getting restore data for " + packageName);
1110 return;
1111 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001112 } finally {
1113 backupData.close();
1114 }
1115
1116 // Okay, we have the data. Now have the agent do the restore.
1117 File newStateName = new File(mStateDir, packageName + ".new");
1118 ParcelFileDescriptor newState =
1119 ParcelFileDescriptor.open(newStateName,
1120 ParcelFileDescriptor.MODE_READ_WRITE |
1121 ParcelFileDescriptor.MODE_CREATE);
1122
1123 backupData = ParcelFileDescriptor.open(backupDataName,
1124 ParcelFileDescriptor.MODE_READ_ONLY);
1125
Christopher Tatec7b31e32009-06-10 15:49:30 -07001126 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001127 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001128 } finally {
1129 newState.close();
1130 backupData.close();
1131 }
1132
1133 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001134 File savedStateName = new File(mStateDir, packageName);
1135 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001136 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001137 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001138 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001139 }
1140 }
1141
Christopher Tateee0e78a2009-07-02 11:17:03 -07001142 class PerformClearThread extends Thread {
1143 IBackupTransport mTransport;
1144 PackageInfo mPackage;
1145
1146 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1147 mTransport = transport;
1148 mPackage = packageInfo;
1149 }
1150
1151 @Override
1152 public void run() {
1153 try {
1154 // Clear the on-device backup state to ensure a full backup next time
1155 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1156 File stateFile = new File(stateDir, mPackage.packageName);
1157 stateFile.delete();
1158
1159 // Tell the transport to remove all the persistent storage for the app
1160 mTransport.clearBackupData(mPackage);
1161 } catch (RemoteException e) {
1162 // can't happen; the transport is local
1163 } finally {
1164 try {
1165 mTransport.finishBackup();
1166 } catch (RemoteException e) {
1167 // can't happen; the transport is local
1168 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001169
1170 // Last but not least, release the cpu
1171 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001172 }
1173 }
1174 }
1175
Christopher Tatedf01dea2009-06-09 20:45:02 -07001176
Christopher Tate487529a2009-04-29 14:03:25 -07001177 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001178
Christopher Tatea8bf8152009-04-30 11:36:21 -07001179 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001180 // Record that we need a backup pass for the caller. Since multiple callers
1181 // may share a uid, we need to note all candidates within that uid and schedule
1182 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001183
1184 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate63d27002009-06-16 17:16:42 -07001185
1186 // If the caller does not hold the BACKUP permission, it can only request a
1187 // backup of its own data.
1188 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001189 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001190 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1191 targets = mBackupParticipants.get(Binder.getCallingUid());
1192 } else {
1193 // a caller with full permission can ask to back up any participating app
1194 // !!! TODO: allow backup of ANY app?
1195 if (DEBUG) Log.v(TAG, "Privileged caller, allowing backup of other apps");
1196 targets = new HashSet<ApplicationInfo>();
1197 int N = mBackupParticipants.size();
1198 for (int i = 0; i < N; i++) {
1199 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1200 if (s != null) {
1201 targets.addAll(s);
1202 }
1203 }
1204 }
Christopher Tate487529a2009-04-29 14:03:25 -07001205 if (targets != null) {
1206 synchronized (mQueueLock) {
1207 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001208 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001209 // validate the caller-supplied package name against the known set of
1210 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001211 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001212 // Add the caller to the set of pending backups. If there is
1213 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001214 BackupRequest req = new BackupRequest(app, false);
1215 mPendingBackups.put(app, req);
Christopher Tatecde87f42009-06-12 12:55:53 -07001216
1217 // Journal this request in case of crash
1218 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001219 }
1220 }
1221
Christopher Tate181fafa2009-05-14 11:12:14 -07001222 if (DEBUG) {
1223 int numKeys = mPendingBackups.size();
Christopher Tate6ef58a12009-06-29 14:56:28 -07001224 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate181fafa2009-05-14 11:12:14 -07001225 for (BackupRequest b : mPendingBackups.values()) {
1226 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1227 }
1228 }
Christopher Tate487529a2009-04-29 14:03:25 -07001229 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001230 } else {
1231 Log.w(TAG, "dataChanged but no participant pkg " + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001232 }
1233 }
Christopher Tate46758122009-05-06 11:22:00 -07001234
Christopher Tatecde87f42009-06-12 12:55:53 -07001235 private void writeToJournalLocked(String str) {
1236 if (mJournalStream != null) {
1237 try {
1238 mJournalStream.writeUTF(str);
1239 } catch (IOException e) {
1240 Log.e(TAG, "Error writing to backup journal");
1241 mJournalStream = null;
1242 mJournal = null;
1243 }
1244 }
1245 }
1246
Christopher Tateee0e78a2009-07-02 11:17:03 -07001247 // Clear the given package's backup data from the current transport
1248 public void clearBackupData(String packageName) {
1249 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1250 PackageInfo info;
1251 try {
1252 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1253 } catch (NameNotFoundException e) {
1254 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1255 return;
1256 }
1257
1258 // If the caller does not hold the BACKUP permission, it can only request a
1259 // wipe of its own backed-up data.
1260 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001261 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001262 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1263 apps = mBackupParticipants.get(Binder.getCallingUid());
1264 } else {
1265 // a caller with full permission can ask to back up any participating app
1266 // !!! TODO: allow data-clear of ANY app?
1267 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1268 apps = new HashSet<ApplicationInfo>();
1269 int N = mBackupParticipants.size();
1270 for (int i = 0; i < N; i++) {
1271 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1272 if (s != null) {
1273 apps.addAll(s);
1274 }
1275 }
1276 }
1277
1278 // now find the given package in the set of candidate apps
1279 for (ApplicationInfo app : apps) {
1280 if (app.packageName.equals(packageName)) {
1281 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1282 // found it; fire off the clear request
1283 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001284 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001285 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1286 new ClearParams(getTransport(mCurrentTransport), info));
1287 mBackupHandler.sendMessage(msg);
1288 }
1289 break;
1290 }
1291 }
1292 }
1293
Christopher Tateace7f092009-06-15 18:07:25 -07001294 // Run a backup pass immediately for any applications that have declared
1295 // that they have pending updates.
1296 public void backupNow() throws RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001297 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001298
Christopher Tateace7f092009-06-15 18:07:25 -07001299 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001300 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001301 try {
1302 if (DEBUG) Log.v(TAG, "sending immediate backup broadcast");
1303 mRunBackupIntent.send();
1304 } catch (PendingIntent.CanceledException e) {
1305 // should never happen
1306 Log.e(TAG, "run-backup intent cancelled!");
1307 }
Christopher Tate46758122009-05-06 11:22:00 -07001308 }
1309 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001310
Christopher Tate8031a3d2009-07-06 16:36:05 -07001311 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001312 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001313 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1314 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001315
1316 boolean wasEnabled = mEnabled;
1317 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001318 Settings.Secure.putInt(mContext.getContentResolver(),
1319 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001320 mEnabled = enable;
1321 }
1322
Christopher Tate49401dd2009-07-01 12:34:29 -07001323 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001324 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001325 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001326 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001327 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001328 // No longer enabled, so stop running backups
1329 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001330 }
1331 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001332 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001333
Christopher Tate8031a3d2009-07-06 16:36:05 -07001334 // Mark the backup service as having been provisioned
1335 public void setBackupProvisioned(boolean available) {
1336 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1337 "setBackupProvisioned");
1338
1339 boolean wasProvisioned = mProvisioned;
1340 synchronized (this) {
1341 Settings.Secure.putInt(mContext.getContentResolver(),
1342 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1343 mProvisioned = available;
1344 }
1345
1346 synchronized (mQueueLock) {
1347 if (available && !wasProvisioned && mEnabled) {
1348 // we're now good to go, so start the backup alarms
1349 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1350 } else if (!available) {
1351 // No longer enabled, so stop running backups
1352 Log.w(TAG, "Backup service no longer provisioned");
1353 mAlarmManager.cancel(mRunBackupIntent);
1354 }
1355 }
1356 }
1357
1358 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1359 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1360 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1361 BACKUP_INTERVAL, mRunBackupIntent);
1362 }
1363
Christopher Tate6ef58a12009-06-29 14:56:28 -07001364 // Report whether the backup mechanism is currently enabled
1365 public boolean isBackupEnabled() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001366 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001367 return mEnabled; // no need to synchronize just to read it
1368 }
1369
Christopher Tate91717492009-06-26 21:07:13 -07001370 // Report the name of the currently active transport
1371 public String getCurrentTransport() {
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001372 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
1373 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001374 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001375 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001376 }
1377
Christopher Tate91717492009-06-26 21:07:13 -07001378 // Report all known, available backup transports
1379 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001380 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001381
Christopher Tate91717492009-06-26 21:07:13 -07001382 String[] list = null;
1383 ArrayList<String> known = new ArrayList<String>();
1384 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1385 if (entry.getValue() != null) {
1386 known.add(entry.getKey());
1387 }
1388 }
1389
1390 if (known.size() > 0) {
1391 list = new String[known.size()];
1392 known.toArray(list);
1393 }
1394 return list;
1395 }
1396
1397 // Select which transport to use for the next backup operation. If the given
1398 // name is not one of the available transports, no action is taken and the method
1399 // returns null.
1400 public String selectBackupTransport(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001401 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001402
1403 synchronized (mTransports) {
1404 String prevTransport = null;
1405 if (mTransports.get(transport) != null) {
1406 prevTransport = mCurrentTransport;
1407 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001408 Settings.Secure.putString(mContext.getContentResolver(),
1409 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001410 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1411 + " returning " + prevTransport);
1412 } else {
1413 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1414 }
1415 return prevTransport;
1416 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001417 }
1418
1419 // Callback: a requested backup agent has been instantiated. This should only
1420 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001421 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001422 synchronized(mAgentConnectLock) {
1423 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1424 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1425 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1426 mConnectedAgent = agent;
1427 mConnecting = false;
1428 } else {
1429 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1430 + " claiming agent connected");
1431 }
1432 mAgentConnectLock.notifyAll();
1433 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001434 }
1435
1436 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1437 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001438 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001439 public void agentDisconnected(String packageName) {
1440 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001441 synchronized(mAgentConnectLock) {
1442 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1443 mConnectedAgent = null;
1444 mConnecting = false;
1445 } else {
1446 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1447 + " claiming agent disconnected");
1448 }
1449 mAgentConnectLock.notifyAll();
1450 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001451 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001452
Christopher Tate8c850b72009-06-07 19:33:20 -07001453 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001454 public IRestoreSession beginRestoreSession(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001455 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001456
1457 synchronized(this) {
1458 if (mActiveRestoreSession != null) {
1459 Log.d(TAG, "Restore session requested but one already active");
1460 return null;
1461 }
Christopher Tate91717492009-06-26 21:07:13 -07001462 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001463 }
1464 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001465 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001466
Christopher Tate9b3905c2009-06-08 15:24:01 -07001467 // ----- Restore session -----
1468
1469 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001470 private static final String TAG = "RestoreSession";
1471
Christopher Tate9b3905c2009-06-08 15:24:01 -07001472 private IBackupTransport mRestoreTransport = null;
1473 RestoreSet[] mRestoreSets = null;
1474
Christopher Tate91717492009-06-26 21:07:13 -07001475 RestoreSession(String transport) {
1476 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001477 }
1478
1479 // --- Binder interface ---
1480 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001481 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001482 "getAvailableRestoreSets");
1483
Christopher Tatef68eb502009-06-16 11:02:01 -07001484 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001485 synchronized(this) {
1486 if (mRestoreSets == null) {
1487 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1488 }
1489 return mRestoreSets;
1490 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001491 } catch (RuntimeException e) {
1492 Log.d(TAG, "getAvailableRestoreSets exception");
1493 e.printStackTrace();
1494 throw e;
1495 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001496 }
1497
Dan Egnor156411d2009-06-26 13:20:02 -07001498 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001499 throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001500 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001501
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001502 Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
1503
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001504 if (mRestoreSets != null) {
1505 for (int i = 0; i < mRestoreSets.length; i++) {
1506 if (token == mRestoreSets[i].token) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001507 mWakelock.acquire();
Christopher Tate7d562ec2009-06-25 18:03:43 -07001508 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001509 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001510 mBackupHandler.sendMessage(msg);
1511 return 0;
1512 }
1513 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001514 } else {
1515 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001516 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001517 return -1;
1518 }
1519
1520 public void endRestoreSession() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001521 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001522 "endRestoreSession");
1523
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001524 Log.d(TAG, "endRestoreSession");
1525
Dan Egnorefe52642009-06-24 00:16:33 -07001526 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001527 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001528 synchronized(BackupManagerService.this) {
1529 if (BackupManagerService.this.mActiveRestoreSession == this) {
1530 BackupManagerService.this.mActiveRestoreSession = null;
1531 } else {
1532 Log.e(TAG, "ending non-current restore session");
1533 }
1534 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001535 }
1536 }
1537
Christopher Tate043dadc2009-06-02 16:11:00 -07001538
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001539 @Override
1540 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1541 synchronized (mQueueLock) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001542 long oldId = Binder.clearCallingIdentity();
1543
Christopher Tate8031a3d2009-07-06 16:36:05 -07001544 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
1545 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07001546 pw.println("Available transports:");
1547 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001548 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1549 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001550 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001551 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001552 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001553 for (int i=0; i<N; i++) {
1554 int uid = mBackupParticipants.keyAt(i);
1555 pw.print(" uid: ");
1556 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001557 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1558 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001559 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001560 }
1561 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001562 pw.println("Pending: " + mPendingBackups.size());
1563 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001564 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001565 }
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001566
1567 Binder.restoreCallingIdentity(oldId);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001568 }
1569 }
Christopher Tate487529a2009-04-29 14:03:25 -07001570}