blob: 20f0750bc8f8da400e18110f1db6a6202c3fd3a2 [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) {
Christopher Tateb407f222009-07-08 13:48:56 -0700813 if (DEBUG) Log.v(TAG, "doBackup() success");
814 if (backupDataName.length() > 0) {
815 backupData =
816 ParcelFileDescriptor.open(backupDataName,
817 ParcelFileDescriptor.MODE_READ_ONLY);
818 if (!transport.performBackup(packInfo, backupData)) {
819 // STOPSHIP TODO: handle errors
820 Log.e(TAG, "Backup failure in performBackup()");
821 }
822 } else {
823 if (DEBUG) {
824 Log.i(TAG, "no backup data written; not calling transport");
825 }
Dan Egnorefe52642009-06-24 00:16:33 -0700826 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700827
Christopher Tateb407f222009-07-08 13:48:56 -0700828 // After successful transport, delete the now-stale data
829 // and juggle the files so that next time we supply the agent
830 // with the new state file it just created.
831 backupDataName.delete();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700832 newStateName.renameTo(savedStateName);
833 }
Christopher Tatec7b31e32009-06-10 15:49:30 -0700834 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700835 Log.e(TAG, "Error backing up " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700836 }
837 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700838 }
839
Christopher Tatedf01dea2009-06-09 20:45:02 -0700840
841 // ----- Restore handling -----
842
Christopher Tateabce4e82009-06-18 18:35:32 -0700843 private boolean signaturesMatch(Signature[] storedSigs, Signature[] deviceSigs) {
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700844 // Allow unsigned apps, but not signed on one device and unsigned on the other
845 // !!! TODO: is this the right policy?
Christopher Tate6aa41f42009-06-19 14:14:22 -0700846 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
847 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -0700848 if ((storedSigs == null || storedSigs.length == 0)
849 && (deviceSigs == null || deviceSigs.length == 0)) {
850 return true;
851 }
852 if (storedSigs == null || deviceSigs == null) {
853 return false;
854 }
855
Christopher Tateabce4e82009-06-18 18:35:32 -0700856 // !!! TODO: this demands that every stored signature match one
857 // that is present on device, and does not demand the converse.
858 // Is this this right policy?
859 int nStored = storedSigs.length;
860 int nDevice = deviceSigs.length;
861
862 for (int i=0; i < nStored; i++) {
863 boolean match = false;
864 for (int j=0; j < nDevice; j++) {
865 if (storedSigs[i].equals(deviceSigs[j])) {
866 match = true;
867 break;
868 }
869 }
870 if (!match) {
871 return false;
872 }
873 }
874 return true;
875 }
876
Christopher Tatedf01dea2009-06-09 20:45:02 -0700877 class PerformRestoreThread extends Thread {
878 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700879 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -0700880 private long mToken;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700881 private RestoreSet mImage;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700882 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -0700883
Christopher Tate5cbbf562009-06-22 16:44:51 -0700884 class RestoreRequest {
885 public PackageInfo app;
886 public int storedAppVersion;
887
888 RestoreRequest(PackageInfo _app, int _version) {
889 app = _app;
890 storedAppVersion = _version;
891 }
892 }
893
Christopher Tate7d562ec2009-06-25 18:03:43 -0700894 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -0700895 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700896 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400897 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -0700898 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700899 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700900
901 try {
902 mStateDir = new File(mBaseStateDir, transport.transportDirName());
903 } catch (RemoteException e) {
904 // can't happen; the transport is local
905 }
906 mStateDir.mkdirs();
Christopher Tatedf01dea2009-06-09 20:45:02 -0700907 }
908
909 @Override
910 public void run() {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400911 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
912 + " mObserver=" + mObserver + " mToken=" + mToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700913 /**
914 * Restore sequence:
915 *
Dan Egnorefe52642009-06-24 00:16:33 -0700916 * 1. get the restore set description for our identity
917 * 2. for each app in the restore set:
Christopher Tatedf01dea2009-06-09 20:45:02 -0700918 * 3.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -0700919 * 3. for each app in the restore queue:
920 * 3.a. clear the app data
921 * 3.b. get the restore data for the app from the transport
922 * 3.c. launch the backup agent for the app
923 * 3.d. agent.doRestore() with the data from the server
924 * 3.e. unbind the agent [and kill the app?]
925 * 4. shut down the transport
Christopher Tatedf01dea2009-06-09 20:45:02 -0700926 */
927
Christopher Tate7d562ec2009-06-25 18:03:43 -0700928 int error = -1; // assume error
929
Dan Egnorefe52642009-06-24 00:16:33 -0700930 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -0700931 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700932 RestoreSet[] images = mTransport.getAvailableRestoreSets();
933 if (images == null) {
934 // STOPSHIP TODO: Handle the failure somehow?
935 Log.e(TAG, "Error getting restore sets");
936 return;
937 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700938
Dan Egnorefe52642009-06-24 00:16:33 -0700939 if (images.length == 0) {
940 Log.i(TAG, "No restore sets available");
941 return;
942 }
Christopher Tatedf01dea2009-06-09 20:45:02 -0700943
Dan Egnorefe52642009-06-24 00:16:33 -0700944 mImage = images[0];
Christopher Tateabce4e82009-06-18 18:35:32 -0700945
Dan Egnorefe52642009-06-24 00:16:33 -0700946 // Get the list of all packages which have backup enabled.
947 // (Include the Package Manager metadata pseudo-package first.)
948 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
949 PackageInfo omPackage = new PackageInfo();
950 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
951 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700952
Dan Egnorefe52642009-06-24 00:16:33 -0700953 List<PackageInfo> agentPackages = allAgentPackages();
954 restorePackages.addAll(agentPackages);
955
Christopher Tate7d562ec2009-06-25 18:03:43 -0700956 // let the observer know that we're running
957 if (mObserver != null) {
958 try {
959 // !!! TODO: get an actual count from the transport after
960 // its startRestore() runs?
961 mObserver.restoreStarting(restorePackages.size());
962 } catch (RemoteException e) {
963 Log.d(TAG, "Restore observer died at restoreStarting");
964 mObserver = null;
965 }
966 }
967
Dan Egnor156411d2009-06-26 13:20:02 -0700968 if (!mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0]))) {
Dan Egnorefe52642009-06-24 00:16:33 -0700969 // STOPSHIP TODO: Handle the failure somehow?
970 Log.e(TAG, "Error starting restore operation");
971 return;
972 }
973
974 String packageName = mTransport.nextRestorePackage();
975 if (packageName == null) {
976 // STOPSHIP TODO: Handle the failure somehow?
977 Log.e(TAG, "Error getting first restore package");
978 return;
979 } else if (packageName.equals("")) {
980 Log.i(TAG, "No restore data available");
981 return;
982 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
983 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
984 + "\", found only \"" + packageName + "\"");
985 return;
986 }
987
988 // Pull the Package Manager metadata from the restore set first
989 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
990 mPackageManager, agentPackages);
991 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
992
Christopher Tate8c032472009-07-02 14:28:47 -0700993 // Verify that the backup set includes metadata. If not, we can't do
994 // signature/version verification etc, so we simply do not proceed with
995 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -0700996 if (!pmAgent.hasMetadata()) {
Christopher Tate8c032472009-07-02 14:28:47 -0700997 Log.i(TAG, "No restore metadata available, so not restoring settings");
998 return;
999 }
1000
Christopher Tate7d562ec2009-06-25 18:03:43 -07001001 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001002 for (;;) {
1003 packageName = mTransport.nextRestorePackage();
1004 if (packageName == null) {
1005 // STOPSHIP TODO: Handle the failure somehow?
1006 Log.e(TAG, "Error getting next restore package");
1007 return;
1008 } else if (packageName.equals("")) {
1009 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001010 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001011
Christopher Tate7d562ec2009-06-25 18:03:43 -07001012 if (mObserver != null) {
1013 ++count;
1014 try {
1015 mObserver.onUpdate(count);
1016 } catch (RemoteException e) {
1017 Log.d(TAG, "Restore observer died in onUpdate");
1018 mObserver = null;
1019 }
1020 }
1021
Dan Egnorefe52642009-06-24 00:16:33 -07001022 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1023 if (metaInfo == null) {
1024 Log.e(TAG, "Missing metadata for " + packageName);
1025 continue;
1026 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001027
Dan Egnorefe52642009-06-24 00:16:33 -07001028 int flags = PackageManager.GET_SIGNATURES;
1029 PackageInfo packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1030 if (metaInfo.versionCode > packageInfo.versionCode) {
1031 Log.w(TAG, "Package " + packageName
1032 + " restore version [" + metaInfo.versionCode
1033 + "] is too new for installed version ["
1034 + packageInfo.versionCode + "]");
1035 continue;
1036 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001037
Dan Egnorefe52642009-06-24 00:16:33 -07001038 if (!signaturesMatch(metaInfo.signatures, packageInfo.signatures)) {
1039 Log.w(TAG, "Signature mismatch restoring " + packageName);
1040 continue;
1041 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001042
Dan Egnorefe52642009-06-24 00:16:33 -07001043 if (DEBUG) Log.v(TAG, "Package " + packageName
1044 + " restore version [" + metaInfo.versionCode
1045 + "] is compatible with installed version ["
1046 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001047
Dan Egnorefe52642009-06-24 00:16:33 -07001048 // Now perform the actual restore
1049 clearApplicationDataSynchronous(packageName);
1050 IBackupAgent agent = bindToAgentSynchronous(
1051 packageInfo.applicationInfo,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001052 IApplicationThread.BACKUP_MODE_RESTORE);
Dan Egnorefe52642009-06-24 00:16:33 -07001053 if (agent == null) {
1054 Log.w(TAG, "Can't find backup agent for " + packageName);
1055 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001056 }
1057
Dan Egnorefe52642009-06-24 00:16:33 -07001058 try {
1059 processOneRestore(packageInfo, metaInfo.versionCode, agent);
1060 } finally {
1061 // unbind even on timeout or failure, just in case
1062 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
1063 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001064 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001065
1066 // if we get this far, report success to the observer
1067 error = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001068 } catch (NameNotFoundException e) {
1069 // STOPSHIP TODO: Handle the failure somehow?
1070 Log.e(TAG, "Invalid paackage restoring data", e);
1071 } catch (RemoteException e) {
1072 // STOPSHIP TODO: Handle the failure somehow?
1073 Log.e(TAG, "Error restoring data", e);
1074 } finally {
1075 try {
1076 mTransport.finishRestore();
1077 } catch (RemoteException e) {
1078 Log.e(TAG, "Error finishing restore", e);
1079 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001080
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001081 Log.d(TAG, "finishing restore mObserver=" + mObserver);
1082
Christopher Tate7d562ec2009-06-25 18:03:43 -07001083 if (mObserver != null) {
1084 try {
1085 mObserver.restoreFinished(error);
1086 } catch (RemoteException e) {
1087 Log.d(TAG, "Restore observer died at restoreFinished");
1088 }
1089 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001090
1091 // done; we can finally release the wakelock
1092 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001093 }
1094 }
1095
Dan Egnorefe52642009-06-24 00:16:33 -07001096 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1097 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001098 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001099 final String packageName = app.packageName;
1100
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001101 Log.d(TAG, "processOneRestore packageName=" + packageName);
1102
Christopher Tatec7b31e32009-06-10 15:49:30 -07001103 // !!! TODO: get the dirs from the transport
1104 File backupDataName = new File(mDataDir, packageName + ".restore");
1105 backupDataName.delete();
1106 try {
1107 ParcelFileDescriptor backupData =
1108 ParcelFileDescriptor.open(backupDataName,
1109 ParcelFileDescriptor.MODE_READ_WRITE |
1110 ParcelFileDescriptor.MODE_CREATE);
1111
1112 // Run the transport's restore pass
1113 // Run the target's backup pass
Christopher Tatec7b31e32009-06-10 15:49:30 -07001114 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001115 if (!mTransport.getRestoreData(backupData)) {
1116 // STOPSHIP TODO: Handle this error somehow?
1117 Log.e(TAG, "Error getting restore data for " + packageName);
1118 return;
1119 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001120 } finally {
1121 backupData.close();
1122 }
1123
1124 // Okay, we have the data. Now have the agent do the restore.
1125 File newStateName = new File(mStateDir, packageName + ".new");
1126 ParcelFileDescriptor newState =
1127 ParcelFileDescriptor.open(newStateName,
1128 ParcelFileDescriptor.MODE_READ_WRITE |
1129 ParcelFileDescriptor.MODE_CREATE);
1130
1131 backupData = ParcelFileDescriptor.open(backupDataName,
1132 ParcelFileDescriptor.MODE_READ_ONLY);
1133
Christopher Tatec7b31e32009-06-10 15:49:30 -07001134 try {
Dan Egnorefe52642009-06-24 00:16:33 -07001135 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001136 } finally {
1137 newState.close();
1138 backupData.close();
1139 }
1140
1141 // if everything went okay, remember the recorded state now
Dan Egnorefe52642009-06-24 00:16:33 -07001142 File savedStateName = new File(mStateDir, packageName);
1143 newStateName.renameTo(savedStateName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001144 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001145 Log.e(TAG, "Error restoring data for " + packageName, e);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001146 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001147 }
1148 }
1149
Christopher Tateee0e78a2009-07-02 11:17:03 -07001150 class PerformClearThread extends Thread {
1151 IBackupTransport mTransport;
1152 PackageInfo mPackage;
1153
1154 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1155 mTransport = transport;
1156 mPackage = packageInfo;
1157 }
1158
1159 @Override
1160 public void run() {
1161 try {
1162 // Clear the on-device backup state to ensure a full backup next time
1163 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1164 File stateFile = new File(stateDir, mPackage.packageName);
1165 stateFile.delete();
1166
1167 // Tell the transport to remove all the persistent storage for the app
1168 mTransport.clearBackupData(mPackage);
1169 } catch (RemoteException e) {
1170 // can't happen; the transport is local
1171 } finally {
1172 try {
1173 mTransport.finishBackup();
1174 } catch (RemoteException e) {
1175 // can't happen; the transport is local
1176 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001177
1178 // Last but not least, release the cpu
1179 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001180 }
1181 }
1182 }
1183
Christopher Tatedf01dea2009-06-09 20:45:02 -07001184
Christopher Tate487529a2009-04-29 14:03:25 -07001185 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001186
Christopher Tatea8bf8152009-04-30 11:36:21 -07001187 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -07001188 // Record that we need a backup pass for the caller. Since multiple callers
1189 // may share a uid, we need to note all candidates within that uid and schedule
1190 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001191
Christopher Tate63d27002009-06-16 17:16:42 -07001192 // If the caller does not hold the BACKUP permission, it can only request a
1193 // backup of its own data.
1194 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001195 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001196 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1197 targets = mBackupParticipants.get(Binder.getCallingUid());
1198 } else {
1199 // a caller with full permission can ask to back up any participating app
1200 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001201 targets = new HashSet<ApplicationInfo>();
1202 int N = mBackupParticipants.size();
1203 for (int i = 0; i < N; i++) {
1204 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1205 if (s != null) {
1206 targets.addAll(s);
1207 }
1208 }
1209 }
Christopher Tate487529a2009-04-29 14:03:25 -07001210 if (targets != null) {
1211 synchronized (mQueueLock) {
1212 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001213 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001214 // validate the caller-supplied package name against the known set of
1215 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001216 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001217 // Add the caller to the set of pending backups. If there is
1218 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001219 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001220 if (mPendingBackups.put(app, req) == null) {
1221 // Journal this request in case of crash. The put()
1222 // operation returned null when this package was not already
1223 // in the set; we want to avoid touching the disk redundantly.
1224 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001225
Christopher Tate22b60d82009-07-07 16:36:02 -07001226 if (DEBUG) {
1227 int numKeys = mPendingBackups.size();
1228 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1229 for (BackupRequest b : mPendingBackups.values()) {
1230 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1231 }
1232 }
1233 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001234 }
1235 }
Christopher Tate487529a2009-04-29 14:03:25 -07001236 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001237 } else {
Christopher Tate22b60d82009-07-07 16:36:02 -07001238 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'");
Christopher Tate487529a2009-04-29 14:03:25 -07001239 }
1240 }
Christopher Tate46758122009-05-06 11:22:00 -07001241
Christopher Tatecde87f42009-06-12 12:55:53 -07001242 private void writeToJournalLocked(String str) {
1243 if (mJournalStream != null) {
1244 try {
1245 mJournalStream.writeUTF(str);
1246 } catch (IOException e) {
1247 Log.e(TAG, "Error writing to backup journal");
1248 mJournalStream = null;
1249 mJournal = null;
1250 }
1251 }
1252 }
1253
Christopher Tateee0e78a2009-07-02 11:17:03 -07001254 // Clear the given package's backup data from the current transport
1255 public void clearBackupData(String packageName) {
1256 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1257 PackageInfo info;
1258 try {
1259 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1260 } catch (NameNotFoundException e) {
1261 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1262 return;
1263 }
1264
1265 // If the caller does not hold the BACKUP permission, it can only request a
1266 // wipe of its own backed-up data.
1267 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001268 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001269 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1270 apps = mBackupParticipants.get(Binder.getCallingUid());
1271 } else {
1272 // a caller with full permission can ask to back up any participating app
1273 // !!! TODO: allow data-clear of ANY app?
1274 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1275 apps = new HashSet<ApplicationInfo>();
1276 int N = mBackupParticipants.size();
1277 for (int i = 0; i < N; i++) {
1278 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1279 if (s != null) {
1280 apps.addAll(s);
1281 }
1282 }
1283 }
1284
1285 // now find the given package in the set of candidate apps
1286 for (ApplicationInfo app : apps) {
1287 if (app.packageName.equals(packageName)) {
1288 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1289 // found it; fire off the clear request
1290 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001291 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001292 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1293 new ClearParams(getTransport(mCurrentTransport), info));
1294 mBackupHandler.sendMessage(msg);
1295 }
1296 break;
1297 }
1298 }
1299 }
1300
Christopher Tateace7f092009-06-15 18:07:25 -07001301 // Run a backup pass immediately for any applications that have declared
1302 // that they have pending updates.
1303 public void backupNow() throws RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001304 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001305
Christopher Tateace7f092009-06-15 18:07:25 -07001306 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001307 synchronized (mQueueLock) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001308 try {
1309 if (DEBUG) Log.v(TAG, "sending immediate backup broadcast");
1310 mRunBackupIntent.send();
1311 } catch (PendingIntent.CanceledException e) {
1312 // should never happen
1313 Log.e(TAG, "run-backup intent cancelled!");
1314 }
Christopher Tate46758122009-05-06 11:22:00 -07001315 }
1316 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001317
Christopher Tate8031a3d2009-07-06 16:36:05 -07001318 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001319 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001320 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1321 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001322
1323 boolean wasEnabled = mEnabled;
1324 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001325 Settings.Secure.putInt(mContext.getContentResolver(),
1326 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001327 mEnabled = enable;
1328 }
1329
Christopher Tate49401dd2009-07-01 12:34:29 -07001330 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001331 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001332 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001333 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001334 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001335 // No longer enabled, so stop running backups
1336 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001337 }
1338 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001339 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001340
Christopher Tate8031a3d2009-07-06 16:36:05 -07001341 // Mark the backup service as having been provisioned
1342 public void setBackupProvisioned(boolean available) {
1343 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1344 "setBackupProvisioned");
1345
1346 boolean wasProvisioned = mProvisioned;
1347 synchronized (this) {
1348 Settings.Secure.putInt(mContext.getContentResolver(),
1349 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1350 mProvisioned = available;
1351 }
1352
1353 synchronized (mQueueLock) {
1354 if (available && !wasProvisioned && mEnabled) {
1355 // we're now good to go, so start the backup alarms
1356 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1357 } else if (!available) {
1358 // No longer enabled, so stop running backups
1359 Log.w(TAG, "Backup service no longer provisioned");
1360 mAlarmManager.cancel(mRunBackupIntent);
1361 }
1362 }
1363 }
1364
1365 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
1366 long when = System.currentTimeMillis() + delayBeforeFirstBackup;
1367 mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, when,
1368 BACKUP_INTERVAL, mRunBackupIntent);
1369 }
1370
Christopher Tate6ef58a12009-06-29 14:56:28 -07001371 // Report whether the backup mechanism is currently enabled
1372 public boolean isBackupEnabled() {
Dianne Hackborncf098292009-07-01 19:55:20 -07001373 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001374 return mEnabled; // no need to synchronize just to read it
1375 }
1376
Christopher Tate91717492009-06-26 21:07:13 -07001377 // Report the name of the currently active transport
1378 public String getCurrentTransport() {
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001379 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
1380 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001381 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001382 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001383 }
1384
Christopher Tate91717492009-06-26 21:07:13 -07001385 // Report all known, available backup transports
1386 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001387 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001388
Christopher Tate91717492009-06-26 21:07:13 -07001389 String[] list = null;
1390 ArrayList<String> known = new ArrayList<String>();
1391 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1392 if (entry.getValue() != null) {
1393 known.add(entry.getKey());
1394 }
1395 }
1396
1397 if (known.size() > 0) {
1398 list = new String[known.size()];
1399 known.toArray(list);
1400 }
1401 return list;
1402 }
1403
1404 // Select which transport to use for the next backup operation. If the given
1405 // name is not one of the available transports, no action is taken and the method
1406 // returns null.
1407 public String selectBackupTransport(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001408 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07001409
1410 synchronized (mTransports) {
1411 String prevTransport = null;
1412 if (mTransports.get(transport) != null) {
1413 prevTransport = mCurrentTransport;
1414 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07001415 Settings.Secure.putString(mContext.getContentResolver(),
1416 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07001417 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
1418 + " returning " + prevTransport);
1419 } else {
1420 Log.w(TAG, "Attempt to select unavailable transport " + transport);
1421 }
1422 return prevTransport;
1423 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001424 }
1425
1426 // Callback: a requested backup agent has been instantiated. This should only
1427 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001428 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001429 synchronized(mAgentConnectLock) {
1430 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1431 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
1432 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
1433 mConnectedAgent = agent;
1434 mConnecting = false;
1435 } else {
1436 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1437 + " claiming agent connected");
1438 }
1439 mAgentConnectLock.notifyAll();
1440 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001441 }
1442
1443 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
1444 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07001445 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07001446 public void agentDisconnected(String packageName) {
1447 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07001448 synchronized(mAgentConnectLock) {
1449 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1450 mConnectedAgent = null;
1451 mConnecting = false;
1452 } else {
1453 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
1454 + " claiming agent disconnected");
1455 }
1456 mAgentConnectLock.notifyAll();
1457 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001458 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001459
Christopher Tate8c850b72009-06-07 19:33:20 -07001460 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07001461 public IRestoreSession beginRestoreSession(String transport) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001462 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07001463
1464 synchronized(this) {
1465 if (mActiveRestoreSession != null) {
1466 Log.d(TAG, "Restore session requested but one already active");
1467 return null;
1468 }
Christopher Tate91717492009-06-26 21:07:13 -07001469 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07001470 }
1471 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07001472 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001473
Christopher Tate9b3905c2009-06-08 15:24:01 -07001474 // ----- Restore session -----
1475
1476 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07001477 private static final String TAG = "RestoreSession";
1478
Christopher Tate9b3905c2009-06-08 15:24:01 -07001479 private IBackupTransport mRestoreTransport = null;
1480 RestoreSet[] mRestoreSets = null;
1481
Christopher Tate91717492009-06-26 21:07:13 -07001482 RestoreSession(String transport) {
1483 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07001484 }
1485
1486 // --- Binder interface ---
1487 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001488 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001489 "getAvailableRestoreSets");
1490
Christopher Tatef68eb502009-06-16 11:02:01 -07001491 try {
Christopher Tate9b3905c2009-06-08 15:24:01 -07001492 synchronized(this) {
Christopher Tate43383042009-07-13 15:17:13 -07001493 if (mRestoreTransport == null) {
1494 Log.w(TAG, "Null transport getting restore sets");
1495 } else if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07001496 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
1497 }
1498 return mRestoreSets;
1499 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001500 } catch (RuntimeException e) {
1501 Log.d(TAG, "getAvailableRestoreSets exception");
1502 e.printStackTrace();
1503 throw e;
1504 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001505 }
1506
Dan Egnor156411d2009-06-26 13:20:02 -07001507 public int performRestore(long token, IRestoreObserver observer)
Christopher Tate7d562ec2009-06-25 18:03:43 -07001508 throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001509 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001510
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001511 Log.d(TAG, "performRestore token=" + token + " observer=" + observer);
1512
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001513 if (mRestoreSets != null) {
1514 for (int i = 0; i < mRestoreSets.length; i++) {
1515 if (token == mRestoreSets[i].token) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001516 mWakelock.acquire();
Christopher Tate7d562ec2009-06-25 18:03:43 -07001517 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Dan Egnor156411d2009-06-26 13:20:02 -07001518 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001519 mBackupHandler.sendMessage(msg);
1520 return 0;
1521 }
1522 }
Christopher Tatef68eb502009-06-16 11:02:01 -07001523 } else {
1524 if (DEBUG) Log.v(TAG, "No current restore set, not doing restore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001525 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001526 return -1;
1527 }
1528
1529 public void endRestoreSession() throws android.os.RemoteException {
Dianne Hackborncf098292009-07-01 19:55:20 -07001530 mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001531 "endRestoreSession");
1532
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001533 Log.d(TAG, "endRestoreSession");
1534
Dan Egnorefe52642009-06-24 00:16:33 -07001535 mRestoreTransport.finishRestore();
Christopher Tate9b3905c2009-06-08 15:24:01 -07001536 mRestoreTransport = null;
Christopher Tatef68eb502009-06-16 11:02:01 -07001537 synchronized(BackupManagerService.this) {
1538 if (BackupManagerService.this.mActiveRestoreSession == this) {
1539 BackupManagerService.this.mActiveRestoreSession = null;
1540 } else {
1541 Log.e(TAG, "ending non-current restore session");
1542 }
1543 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07001544 }
1545 }
1546
Christopher Tate043dadc2009-06-02 16:11:00 -07001547
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001548 @Override
1549 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1550 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001551 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
1552 + " / " + (!mProvisioned ? "not " : "") + "provisioned");
Christopher Tate91717492009-06-26 21:07:13 -07001553 pw.println("Available transports:");
1554 for (String t : listAllTransports()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001555 String pad = (t.equals(mCurrentTransport)) ? " * " : " ";
1556 pw.println(pad + t);
Christopher Tate91717492009-06-26 21:07:13 -07001557 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001558 int N = mBackupParticipants.size();
Christopher Tatece0bf062009-07-01 11:43:53 -07001559 pw.println("Participants: " + N);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001560 for (int i=0; i<N; i++) {
1561 int uid = mBackupParticipants.keyAt(i);
1562 pw.print(" uid: ");
1563 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07001564 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
1565 for (ApplicationInfo app: participants) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001566 pw.println(" " + app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001567 }
1568 }
Christopher Tate6aa41f42009-06-19 14:14:22 -07001569 pw.println("Pending: " + mPendingBackups.size());
1570 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07001571 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07001572 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001573 }
1574 }
Christopher Tate487529a2009-04-29 14:03:25 -07001575}