blob: 3307932e928cbeaf1f9ab34e9578b6fc7d73f9ae [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;
Dan Egnorbb9001c2009-07-27 12:20:13 -070049import android.os.SystemClock;
50import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.util.Log;
52import android.util.SparseArray;
53
54import android.backup.IBackupManager;
Christopher Tate7d562ec2009-06-25 18:03:43 -070055import android.backup.IRestoreObserver;
Christopher Tate8c850b72009-06-07 19:33:20 -070056import android.backup.IRestoreSession;
Christopher Tate9b3905c2009-06-08 15:24:01 -070057import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070058
Christopher Tated55e18a2009-09-21 10:12:59 -070059import com.android.internal.backup.BackupConstants;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070060import com.android.internal.backup.LocalTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -070061import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070062
Christopher Tate6785dd82009-06-18 15:58:25 -070063import com.android.server.PackageManagerBackupAgent;
Christopher Tate6aa41f42009-06-19 14:14:22 -070064import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070065
Christopher Tatecde87f42009-06-12 12:55:53 -070066import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070067import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068import java.io.FileDescriptor;
Christopher Tate4cc86e12009-09-21 19:36:51 -070069import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070070import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070072import java.io.RandomAccessFile;
Christopher Tate487529a2009-04-29 14:03:25 -070073import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040074import java.util.ArrayList;
75import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070076import java.util.HashSet;
77import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070078import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070079import java.util.Random;
Christopher Tate487529a2009-04-29 14:03:25 -070080
81class BackupManagerService extends IBackupManager.Stub {
82 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070083 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070084
Christopher Tate49401dd2009-07-01 12:34:29 -070085 // How often we perform a backup pass. Privileged external callers can
86 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070087 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070088
Dan Egnorc1c49c02009-10-30 17:35:39 -070089 // Random variation in backup scheduling time to avoid server load spikes
90 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
91
Christopher Tate8031a3d2009-07-06 16:36:05 -070092 // The amount of time between the initial provisioning of the device and
93 // the first backup pass.
94 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
95
Christopher Tate4cc86e12009-09-21 19:36:51 -070096 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
97 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
98 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070099 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700100 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700101 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700102 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700103 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700104
105 // Timeout interval for deciding that a bind or clear-data has taken too long
106 static final long TIMEOUT_INTERVAL = 10 * 1000;
107
Christopher Tate487529a2009-04-29 14:03:25 -0700108 private Context mContext;
109 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700110 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700111 private PowerManager mPowerManager;
112 private AlarmManager mAlarmManager;
113
Christopher Tate73e02522009-07-15 14:18:26 -0700114 boolean mEnabled; // access to this is synchronized on 'this'
115 boolean mProvisioned;
116 PowerManager.WakeLock mWakelock;
117 final BackupHandler mBackupHandler = new BackupHandler();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700118 PendingIntent mRunBackupIntent, mRunInitIntent;
119 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700120 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700121 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700122 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700123 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700124 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700125 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700126 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700127
Christopher Tate181fafa2009-05-14 11:12:14 -0700128 BackupRequest(ApplicationInfo app, boolean isFull) {
129 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700130 fullBackup = isFull;
131 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700132
133 public String toString() {
134 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
135 }
Christopher Tate46758122009-05-06 11:22:00 -0700136 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400137 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700138 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700139 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700140
141 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700142 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700143
144 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700145 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700146
Christopher Tate043dadc2009-06-02 16:11:00 -0700147 // The thread performing the sequence of queued backups binds to each app's agent
148 // in succession. Bind notifications are asynchronously delivered through the
149 // Activity Manager; use this lock object to signal when a requested binding has
150 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700151 final Object mAgentConnectLock = new Object();
152 IBackupAgent mConnectedAgent;
153 volatile boolean mConnecting;
Christopher Tate21ab6a52009-09-24 18:01:46 -0700154 volatile boolean mBackupOrRestoreInProgress = false;
Christopher Tate55f931a2009-09-29 17:17:34 -0700155 volatile long mLastBackupPass;
156 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700157
Christopher Tate55f931a2009-09-29 17:17:34 -0700158 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700159 final Object mClearDataLock = new Object();
160 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700161
Christopher Tate91717492009-06-26 21:07:13 -0700162 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700163 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700164 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700165 String mCurrentTransport;
166 IBackupTransport mLocalTransport, mGoogleTransport;
167 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700168
Christopher Tate73e02522009-07-15 14:18:26 -0700169 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700170 public IBackupTransport transport;
171 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700172 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700173
Dan Egnor156411d2009-06-26 13:20:02 -0700174 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700175 transport = _transport;
176 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700177 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700178 }
179 }
180
Christopher Tate73e02522009-07-15 14:18:26 -0700181 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700182 public IBackupTransport transport;
183 public PackageInfo packageInfo;
184
185 ClearParams(IBackupTransport _transport, PackageInfo _info) {
186 transport = _transport;
187 packageInfo = _info;
188 }
189 }
190
Christopher Tate5cb400b2009-06-25 16:03:14 -0700191 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700192 File mBaseStateDir;
193 File mDataDir;
194 File mJournalDir;
195 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700196
197 // Keep a log of all the apps we've ever backed up
198 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700199 HashSet<String> mEverStoredApps = new HashSet<String>();
200
Christopher Tate4cc86e12009-09-21 19:36:51 -0700201 // Persistently track the need to do a full init
202 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
203 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tate21ab6a52009-09-24 18:01:46 -0700204 volatile boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700205
Christopher Tate487529a2009-04-29 14:03:25 -0700206 public BackupManagerService(Context context) {
207 mContext = context;
208 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700209 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700210
Christopher Tateb6787f22009-07-02 17:40:45 -0700211 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
212 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
213
Christopher Tate22b87872009-05-04 16:41:53 -0700214 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700215 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700216 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700217 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700218 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700219 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tatef4172472009-05-05 15:50:03 -0700220 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700221
Christopher Tate4cc86e12009-09-21 19:36:51 -0700222 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700223 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700224 IntentFilter filter = new IntentFilter();
225 filter.addAction(RUN_BACKUP_ACTION);
226 context.registerReceiver(mRunBackupReceiver, filter,
227 android.Manifest.permission.BACKUP, null);
228
229 mRunInitReceiver = new RunInitializeReceiver();
230 filter = new IntentFilter();
231 filter.addAction(RUN_INITIALIZE_ACTION);
232 context.registerReceiver(mRunInitReceiver, filter,
233 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700234
235 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700236 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
237 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
238
Christopher Tate4cc86e12009-09-21 19:36:51 -0700239 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
240 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
241 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
242
Christopher Tatecde87f42009-06-12 12:55:53 -0700243 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700244 mJournalDir = new File(mBaseStateDir, "pending");
245 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700246 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700247
Christopher Tate73e02522009-07-15 14:18:26 -0700248 // Set up the various sorts of package tracking we do
249 initPackageTracking();
250
Christopher Tateabce4e82009-06-18 18:35:32 -0700251 // Build our mapping of uid to backup client services. This implicitly
252 // schedules a backup pass on the Package Manager metadata the first
253 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700254 synchronized (mBackupParticipants) {
255 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700256 }
257
Dan Egnor87a02bc2009-06-17 02:30:10 -0700258 // Set up our transport options and initialize the default transport
259 // TODO: Have transports register themselves somehow?
260 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700261 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700262 ComponentName localName = new ComponentName(context, LocalTransport.class);
263 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700264
Christopher Tate91717492009-06-26 21:07:13 -0700265 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700266 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
267 Settings.Secure.BACKUP_TRANSPORT);
268 if ("".equals(mCurrentTransport)) {
269 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700270 }
Christopher Tate91717492009-06-26 21:07:13 -0700271 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
272
273 // Attach to the Google backup transport. When this comes up, it will set
274 // itself as the current transport because we explicitly reset mCurrentTransport
275 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700276 Intent intent = new Intent().setComponent(new ComponentName(
277 "com.google.android.backup",
278 "com.google.android.backup.BackupTransportService"));
279 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700280
Christopher Tatecde87f42009-06-12 12:55:53 -0700281 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700282 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700283 parseLeftoverJournals();
284
Christopher Tateb6787f22009-07-02 17:40:45 -0700285 // Power management
286 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
287
288 // Start the backup passes going
289 setBackupEnabled(areEnabled);
290 }
291
292 private class RunBackupReceiver extends BroadcastReceiver {
293 public void onReceive(Context context, Intent intent) {
294 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700295 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700296 if (mPendingInits.size() > 0) {
297 // If there are pending init operations, we process those
298 // and then settle into the usual periodic backup schedule.
299 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
300 try {
301 mAlarmManager.cancel(mRunInitIntent);
302 mRunInitIntent.send();
303 } catch (PendingIntent.CanceledException ce) {
304 Log.e(TAG, "Run init intent cancelled");
305 // can't really do more than bail here
306 }
307 } else {
308 // Don't run backups now if we're disabled, not yet
Christopher Tate21ab6a52009-09-24 18:01:46 -0700309 // fully set up, in the middle of a backup already,
310 // or racing with an initialize pass.
311 if (mEnabled && mProvisioned
312 && !mBackupOrRestoreInProgress && !mInitInProgress) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700313 if (DEBUG) Log.v(TAG, "Running a backup pass");
Christopher Tate21ab6a52009-09-24 18:01:46 -0700314 mBackupOrRestoreInProgress = true;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700315
316 // Acquire the wakelock and pass it to the backup thread. it will
317 // be released once backup concludes.
318 mWakelock.acquire();
319
320 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
321 mBackupHandler.sendMessage(msg);
322 } else {
323 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned
Christopher Tate21ab6a52009-09-24 18:01:46 -0700324 + " b=" + mBackupOrRestoreInProgress + " i=" + mInitInProgress);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700325 }
326 }
327 }
328 }
329 }
330 }
331
332 private class RunInitializeReceiver extends BroadcastReceiver {
333 public void onReceive(Context context, Intent intent) {
334 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
335 synchronized (mQueueLock) {
336 if (DEBUG) Log.v(TAG, "Running a device init");
337 mInitInProgress = true;
338
339 // Acquire the wakelock and pass it to the init thread. it will
340 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700341 mWakelock.acquire();
342
Christopher Tate4cc86e12009-09-21 19:36:51 -0700343 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700344 mBackupHandler.sendMessage(msg);
345 }
346 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700347 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700348 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700349
Christopher Tate73e02522009-07-15 14:18:26 -0700350 private void initPackageTracking() {
351 if (DEBUG) Log.v(TAG, "Initializing package tracking");
352
Christopher Tatee97e8072009-07-15 16:45:50 -0700353 // Keep a log of what apps we've ever backed up. Because we might have
354 // rebooted in the middle of an operation that was removing something from
355 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700356 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700357 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700358
Christopher Tatee97e8072009-07-15 16:45:50 -0700359 // If we were in the middle of removing something from the ever-backed-up
360 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700361 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700362 if (tempProcessedFile.exists()) {
363 tempProcessedFile.delete();
364 }
365
Dan Egnor852f8e42009-09-30 11:20:45 -0700366 // If there are previous contents, parse them out then start a new
367 // file to continue the recordkeeping.
368 if (mEverStored.exists()) {
369 RandomAccessFile temp = null;
370 RandomAccessFile in = null;
371
372 try {
373 temp = new RandomAccessFile(tempProcessedFile, "rws");
374 in = new RandomAccessFile(mEverStored, "r");
375
376 while (true) {
377 PackageInfo info;
378 String pkg = in.readUTF();
379 try {
380 info = mPackageManager.getPackageInfo(pkg, 0);
381 mEverStoredApps.add(pkg);
382 temp.writeUTF(pkg);
383 if (DEBUG) Log.v(TAG, " + " + pkg);
384 } catch (NameNotFoundException e) {
385 // nope, this package was uninstalled; don't include it
386 if (DEBUG) Log.v(TAG, " - " + pkg);
387 }
388 }
389 } catch (EOFException e) {
390 // Once we've rewritten the backup history log, atomically replace the
391 // old one with the new one then reopen the file for continuing use.
392 if (!tempProcessedFile.renameTo(mEverStored)) {
393 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
394 }
395 } catch (IOException e) {
396 Log.e(TAG, "Error in processed file", e);
397 } finally {
398 try { if (temp != null) temp.close(); } catch (IOException e) {}
399 try { if (in != null) in.close(); } catch (IOException e) {}
400 }
401 }
402
Christopher Tate73e02522009-07-15 14:18:26 -0700403 // Register for broadcasts about package install, etc., so we can
404 // update the provider list.
405 IntentFilter filter = new IntentFilter();
406 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
407 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
408 filter.addDataScheme("package");
409 mContext.registerReceiver(mBroadcastReceiver, filter);
410 }
411
Christopher Tatecde87f42009-06-12 12:55:53 -0700412 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700413 for (File f : mJournalDir.listFiles()) {
414 if (mJournal == null || f.compareTo(mJournal) != 0) {
415 // This isn't the current journal, so it must be a leftover. Read
416 // out the package names mentioned there and schedule them for
417 // backup.
418 RandomAccessFile in = null;
419 try {
420 Log.i(TAG, "Found stale backup journal, scheduling:");
421 in = new RandomAccessFile(f, "r");
422 while (true) {
423 String packageName = in.readUTF();
424 Log.i(TAG, " + " + packageName);
425 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700426 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700427 } catch (EOFException e) {
428 // no more data; we're done
429 } catch (Exception e) {
430 Log.e(TAG, "Can't read " + f, e);
431 } finally {
432 // close/delete the file
433 try { if (in != null) in.close(); } catch (IOException e) {}
434 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700435 }
436 }
437 }
438 }
439
Christopher Tate4cc86e12009-09-21 19:36:51 -0700440 // Maintain persistent state around whether need to do an initialize operation.
441 // Must be called with the queue lock held.
442 void recordInitPendingLocked(boolean isPending, String transportName) {
443 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
444 + " on transport " + transportName);
445 try {
446 IBackupTransport transport = getTransport(transportName);
447 String transportDirName = transport.transportDirName();
448 File stateDir = new File(mBaseStateDir, transportDirName);
449 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
450
451 if (isPending) {
452 // We need an init before we can proceed with sending backup data.
453 // Record that with an entry in our set of pending inits, as well as
454 // journaling it via creation of a sentinel file.
455 mPendingInits.add(transportName);
456 try {
457 (new FileOutputStream(initPendingFile)).close();
458 } catch (IOException ioe) {
459 // Something is badly wrong with our permissions; just try to move on
460 }
461 } else {
462 // No more initialization needed; wipe the journal and reset our state.
463 initPendingFile.delete();
464 mPendingInits.remove(transportName);
465 }
466 } catch (RemoteException e) {
467 // can't happen; the transport is local
468 }
469 }
470
Christopher Tated55e18a2009-09-21 10:12:59 -0700471 // Reset all of our bookkeeping, in response to having been told that
472 // the backend data has been wiped [due to idle expiry, for example],
473 // so we must re-upload all saved settings.
474 void resetBackupState(File stateFileDir) {
475 synchronized (mQueueLock) {
476 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700477 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700478 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700479
480 // Remove all the state files
481 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700482 // ... but don't touch the needs-init sentinel
483 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
484 sf.delete();
485 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700486 }
487
488 // Enqueue a new backup of every participant
489 int N = mBackupParticipants.size();
490 for (int i=0; i<N; i++) {
491 int uid = mBackupParticipants.keyAt(i);
492 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
493 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700494 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700495 }
496 }
497 }
498 }
499
Christopher Tate91717492009-06-26 21:07:13 -0700500 // Add a transport to our set of available backends
501 private void registerTransport(String name, IBackupTransport transport) {
502 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700503 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tate91717492009-06-26 21:07:13 -0700504 mTransports.put(name, transport);
505 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700506
507 // If the init sentinel file exists, we need to be sure to perform the init
508 // as soon as practical. We also create the state directory at registration
509 // time to ensure it's present from the outset.
510 try {
511 String transportName = transport.transportDirName();
512 File stateDir = new File(mBaseStateDir, transportName);
513 stateDir.mkdirs();
514
515 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
516 if (initSentinel.exists()) {
517 synchronized (mQueueLock) {
518 mPendingInits.add(transportName);
519
520 // TODO: pick a better starting time than now + 1 minute
521 long delay = 1000 * 60; // one minute, in milliseconds
522 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
523 System.currentTimeMillis() + delay, mRunInitIntent);
524 }
525 }
526 } catch (RemoteException e) {
527 // can't happen, the transport is local
528 }
Christopher Tate91717492009-06-26 21:07:13 -0700529 }
530
Christopher Tate3799bc22009-05-06 16:13:56 -0700531 // ----- Track installation/removal of packages -----
532 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
533 public void onReceive(Context context, Intent intent) {
534 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
535
536 Uri uri = intent.getData();
537 if (uri == null) {
538 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700539 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700540 String pkgName = uri.getSchemeSpecificPart();
541 if (pkgName == null) {
542 return;
543 }
544
545 String action = intent.getAction();
546 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
547 synchronized (mBackupParticipants) {
548 Bundle extras = intent.getExtras();
549 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
550 // The package was just upgraded
551 updatePackageParticipantsLocked(pkgName);
552 } else {
553 // The package was just added
554 addPackageParticipantsLocked(pkgName);
555 }
556 }
557 }
558 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
559 Bundle extras = intent.getExtras();
560 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
561 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
562 } else {
563 synchronized (mBackupParticipants) {
564 removePackageParticipantsLocked(pkgName);
565 }
566 }
567 }
568 }
569 };
570
Dan Egnor87a02bc2009-06-17 02:30:10 -0700571 // ----- Track connection to GoogleBackupTransport service -----
572 ServiceConnection mGoogleConnection = new ServiceConnection() {
573 public void onServiceConnected(ComponentName name, IBinder service) {
574 if (DEBUG) Log.v(TAG, "Connected to Google transport");
575 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700576 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700577 }
578
579 public void onServiceDisconnected(ComponentName name) {
580 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
581 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700582 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700583 }
584 };
585
Joe Onorato8ad02812009-05-13 01:41:44 -0400586 // ----- Run the actual backup process asynchronously -----
587
Christopher Tate181fafa2009-05-14 11:12:14 -0700588 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400589 public void handleMessage(Message msg) {
590
591 switch (msg.what) {
592 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700593 {
Christopher Tate55f931a2009-09-29 17:17:34 -0700594 mLastBackupPass = System.currentTimeMillis();
595 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
596
Christopher Tate91717492009-06-26 21:07:13 -0700597 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700598 if (transport == null) {
599 Log.v(TAG, "Backup requested but no transport available");
Christopher Tatea253f162009-09-27 15:16:44 -0700600 synchronized (mQueueLock) {
601 mBackupOrRestoreInProgress = false;
602 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700603 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700604 break;
605 }
606
Joe Onorato8ad02812009-05-13 01:41:44 -0400607 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700608 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400609 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700610 // Do we have any work to do?
611 if (mPendingBackups.size() > 0) {
612 for (BackupRequest b: mPendingBackups.values()) {
613 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700614 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700615 Log.v(TAG, "clearing pending backups");
616 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700617
Christopher Tate49401dd2009-07-01 12:34:29 -0700618 // Start a new backup-queue journal file too
Dan Egnor852f8e42009-09-30 11:20:45 -0700619 File oldJournal = mJournal;
620 mJournal = null;
Christopher Tate49401dd2009-07-01 12:34:29 -0700621
622 // At this point, we have started a new journal file, and the old
623 // file identity is being passed to the backup processing thread.
624 // When it completes successfully, that old journal file will be
625 // deleted. If we crash prior to that, the old journal is parsed
626 // at next boot and the journaled requests fulfilled.
627 (new PerformBackupThread(transport, queue, oldJournal)).start();
628 } else {
629 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tatea253f162009-09-27 15:16:44 -0700630 synchronized (mQueueLock) {
631 mBackupOrRestoreInProgress = false;
632 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700633 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700634 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400635 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700636 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700637 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700638
639 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400640 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700641
642 case MSG_RUN_RESTORE:
643 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700644 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400645 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700646 (new PerformRestoreThread(params.transport, params.observer,
647 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700648 break;
649 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700650
651 case MSG_RUN_CLEAR:
652 {
653 ClearParams params = (ClearParams)msg.obj;
654 (new PerformClearThread(params.transport, params.packageInfo)).start();
655 break;
656 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700657
658 case MSG_RUN_INITIALIZE:
659 {
660 HashSet<String> queue;
661
662 // Snapshot the pending-init queue and work on that
663 synchronized (mQueueLock) {
664 queue = new HashSet<String>(mPendingInits);
665 mPendingInits.clear();
666 }
667
668 (new PerformInitializeThread(queue)).start();
669 break;
670 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400671 }
672 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400673 }
674
Christopher Tate181fafa2009-05-14 11:12:14 -0700675 // Add the backup agents in the given package to our set of known backup participants.
676 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700677 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700678 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700679 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700680 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700681 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700682 }
683
Christopher Tate181fafa2009-05-14 11:12:14 -0700684 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700685 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700686 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700687 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
688 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700689 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700690 + " uid=" + p.applicationInfo.uid
691 + " killAfterRestore="
692 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
693 + " restoreNeedsApplication="
694 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
695 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700696 }
697 }
698
Dan Egnorefe52642009-06-24 00:16:33 -0700699 for (PackageInfo pkg : targetPkgs) {
700 if (packageName == null || pkg.packageName.equals(packageName)) {
701 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700702 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700703 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700704 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700705 mBackupParticipants.put(uid, set);
706 }
Dan Egnorefe52642009-06-24 00:16:33 -0700707 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700708
709 // If we've never seen this app before, schedule a backup for it
710 if (!mEverStoredApps.contains(pkg.packageName)) {
711 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
712 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700713 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700714 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700715 }
Christopher Tate487529a2009-04-29 14:03:25 -0700716 }
717 }
718
Christopher Tate6785dd82009-06-18 15:58:25 -0700719 // Remove the given package's entry from our known active set. If
720 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700721 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700722 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700723 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700724 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700725 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700726 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700727 int flags = PackageManager.GET_SIGNATURES;
728 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700729 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700730 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700731 }
732 } else {
733 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700734 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700735 }
736 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700737 }
738
Joe Onorato8ad02812009-05-13 01:41:44 -0400739 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700740 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700741 if (DEBUG) {
742 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
743 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700744 for (PackageInfo p : agents) {
745 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700746 }
747 }
Dan Egnorefe52642009-06-24 00:16:33 -0700748 for (PackageInfo pkg : agents) {
749 if (packageName == null || pkg.packageName.equals(packageName)) {
750 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700751 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700752 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700753 // Find the existing entry with the same package name, and remove it.
754 // We can't just remove(app) because the instances are different.
755 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700756 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700757 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700758 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700759 break;
760 }
761 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700762 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700763 mBackupParticipants.delete(uid);
764 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700765 }
766 }
767 }
768 }
769
Christopher Tate181fafa2009-05-14 11:12:14 -0700770 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700771 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700772 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700773 int flags = PackageManager.GET_SIGNATURES;
774 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
775 int N = packages.size();
776 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700777 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700778 try {
779 ApplicationInfo app = pkg.applicationInfo;
780 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
781 || app.backupAgentName == null
782 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
783 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
784 packages.remove(a);
785 }
786 else {
787 // we will need the shared library path, so look that up and store it here
788 app = mPackageManager.getApplicationInfo(pkg.packageName,
789 PackageManager.GET_SHARED_LIBRARY_FILES);
790 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
791 }
792 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700793 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700794 }
795 }
Dan Egnorefe52642009-06-24 00:16:33 -0700796 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700797 }
Christopher Tateaa088442009-06-16 18:25:46 -0700798
Christopher Tate3799bc22009-05-06 16:13:56 -0700799 // Reset the given package's known backup participants. Unlike add/remove, the update
800 // action cannot be passed a null package name.
801 void updatePackageParticipantsLocked(String packageName) {
802 if (packageName == null) {
803 Log.e(TAG, "updatePackageParticipants called with null package name");
804 return;
805 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700806 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700807
808 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700809 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700810 removePackageParticipantsLockedInner(packageName, allApps);
811 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700812 }
813
Christopher Tate73e02522009-07-15 14:18:26 -0700814 // Called from the backup thread: record that the given app has been successfully
815 // backed up at least once
816 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700817 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
818
819 synchronized (mEverStoredApps) {
820 if (!mEverStoredApps.add(packageName)) return;
821
822 RandomAccessFile out = null;
823 try {
824 out = new RandomAccessFile(mEverStored, "rws");
825 out.seek(out.length());
826 out.writeUTF(packageName);
827 } catch (IOException e) {
828 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
829 } finally {
830 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700831 }
832 }
833 }
834
Christopher Tatee97e8072009-07-15 16:45:50 -0700835 // Remove our awareness of having ever backed up the given package
836 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700837 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700838
Dan Egnor852f8e42009-09-30 11:20:45 -0700839 synchronized (mEverStoredApps) {
840 // Rewrite the file and rename to overwrite. If we reboot in the middle,
841 // we'll recognize on initialization time that the package no longer
842 // exists and fix it up then.
843 File tempKnownFile = new File(mBaseStateDir, "processed.new");
844 RandomAccessFile known = null;
845 try {
846 known = new RandomAccessFile(tempKnownFile, "rws");
847 mEverStoredApps.remove(packageName);
848 for (String s : mEverStoredApps) {
849 known.writeUTF(s);
850 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700851 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700852 known.close();
853 known = null;
854 if (!tempKnownFile.renameTo(mEverStored)) {
855 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
856 }
857 } catch (IOException e) {
858 // Bad: we couldn't create the new copy. For safety's sake we
859 // abandon the whole process and remove all what's-backed-up
860 // state entirely, meaning we'll force a backup pass for every
861 // participant on the next boot or [re]install.
862 Log.w(TAG, "Error rewriting " + mEverStored, e);
863 mEverStoredApps.clear();
864 tempKnownFile.delete();
865 mEverStored.delete();
866 } finally {
867 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700868 }
869 }
870 }
871
Dan Egnor87a02bc2009-06-17 02:30:10 -0700872 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700873 private IBackupTransport getTransport(String transportName) {
874 synchronized (mTransports) {
875 IBackupTransport transport = mTransports.get(transportName);
876 if (transport == null) {
877 Log.w(TAG, "Requested unavailable transport: " + transportName);
878 }
879 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700880 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700881 }
882
Christopher Tatedf01dea2009-06-09 20:45:02 -0700883 // fire off a backup agent, blocking until it attaches or times out
884 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
885 IBackupAgent agent = null;
886 synchronized(mAgentConnectLock) {
887 mConnecting = true;
888 mConnectedAgent = null;
889 try {
890 if (mActivityManager.bindBackupAgent(app, mode)) {
891 Log.d(TAG, "awaiting agent for " + app);
892
893 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700894 // only wait 10 seconds for the clear data to happen
895 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
896 while (mConnecting && mConnectedAgent == null
897 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700898 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700899 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700900 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700901 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700902 return null;
903 }
904 }
905
906 // if we timed out with no connect, abort and move on
907 if (mConnecting == true) {
908 Log.w(TAG, "Timeout waiting for agent " + app);
909 return null;
910 }
911 agent = mConnectedAgent;
912 }
913 } catch (RemoteException e) {
914 // can't happen
915 }
916 }
917 return agent;
918 }
919
Christopher Tatec7b31e32009-06-10 15:49:30 -0700920 // clear an application's data, blocking until the operation completes or times out
921 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700922 // Don't wipe packages marked allowClearUserData=false
923 try {
924 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
925 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
926 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
927 + packageName);
928 return;
929 }
930 } catch (NameNotFoundException e) {
931 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
932 return;
933 }
934
Christopher Tatec7b31e32009-06-10 15:49:30 -0700935 ClearDataObserver observer = new ClearDataObserver();
936
937 synchronized(mClearDataLock) {
938 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700939 /* This is causing some critical processes to be killed during setup.
940 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700941 try {
942 mActivityManager.clearApplicationUserData(packageName, observer);
943 } catch (RemoteException e) {
944 // can't happen because the activity manager is in this process
945 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700946 */
947 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700948
949 // only wait 10 seconds for the clear data to happen
950 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
951 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
952 try {
953 mClearDataLock.wait(5000);
954 } catch (InterruptedException e) {
955 // won't happen, but still.
956 mClearingData = false;
957 }
958 }
959 }
960 }
961
962 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -0700963 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700964 synchronized(mClearDataLock) {
965 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700966 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700967 }
968 }
969 }
970
Christopher Tate043dadc2009-06-02 16:11:00 -0700971 // ----- Back up a set of applications via a worker thread -----
972
973 class PerformBackupThread extends Thread {
974 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700975 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700976 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700977 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700978 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700979
Christopher Tateaa088442009-06-16 18:25:46 -0700980 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700981 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700982 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700983 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700984 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700985
986 try {
987 mStateDir = new File(mBaseStateDir, transport.transportDirName());
988 } catch (RemoteException e) {
989 // can't happen; the transport is local
990 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700991 }
992
993 @Override
994 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -0700995 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -0700996 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -0700997 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
998
Christopher Tate79588342009-06-30 16:11:49 -0700999 // Backups run at background priority
1000 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1001
Christopher Tate043dadc2009-06-02 16:11:00 -07001002 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001003 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001004
Dan Egnor852f8e42009-09-30 11:20:45 -07001005 // If we haven't stored package manager metadata yet, we must init the transport.
1006 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1007 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1008 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1009 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001010 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001011 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001012 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001013 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001014 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Dan Egnor726247c2009-09-29 19:12:31 -07001015 Log.e(TAG, "Transport error in initializeDevice()");
1016 }
Dan Egnor01445162009-09-21 17:04:05 -07001017 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001018
1019 // The package manager doesn't have a proper <application> etc, but since
1020 // it's running here in the system process we can just set up its agent
1021 // directly and use a synthetic BackupRequest. We always run this pass
1022 // because it's cheap and this way we guarantee that we don't get out of
1023 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001024 if (status == BackupConstants.TRANSPORT_OK) {
1025 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1026 mPackageManager, allAgentPackages());
1027 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1028 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1029 status = processOneBackup(pmRequest,
1030 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1031 }
Christopher Tate90967f42009-09-20 15:28:33 -07001032
Dan Egnor01445162009-09-21 17:04:05 -07001033 if (status == BackupConstants.TRANSPORT_OK) {
1034 // Now run all the backups in our queue
1035 status = doQueuedBackups(mTransport);
1036 }
1037
1038 if (status == BackupConstants.TRANSPORT_OK) {
1039 // Tell the transport to finish everything it has buffered
1040 status = mTransport.finishBackup();
1041 if (status == BackupConstants.TRANSPORT_OK) {
1042 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001043 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001044 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001045 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001046 Log.e(TAG, "Transport error in finishBackup()");
1047 }
1048 }
1049
Dan Egnor01445162009-09-21 17:04:05 -07001050 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001051 // The backend reports that our dataset has been wiped. We need to
1052 // reset all of our bookkeeping and instead run a new backup pass for
Dan Egnor852f8e42009-09-30 11:20:45 -07001053 // everything. This must come after mBackupOrRestoreInProgress is cleared.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001054 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001055 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001056 }
1057 } catch (Exception e) {
1058 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001059 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001060 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001061 // If things went wrong, we need to re-stage the apps we had expected
1062 // to be backing up in this pass. This journals the package names in
1063 // the current active pending-backup file, not in the we are holding
1064 // here in mJournal.
1065 if (status != BackupConstants.TRANSPORT_OK) {
1066 Log.w(TAG, "Backup pass unsuccessful, restaging");
1067 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001068 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001069 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001070
1071 // We also want to reset the backup schedule based on whatever
1072 // the transport suggests by way of retry/backoff time.
1073 try {
1074 startBackupAlarmsLocked(mTransport.requestBackupTime());
1075 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001076 }
1077
1078 // Either backup was successful, in which case we of course do not need
1079 // this pass's journal any more; or it failed, in which case we just
1080 // re-enqueued all of these packages in the current active journal.
1081 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001082 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001083 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1084 }
1085
Christopher Tate21ab6a52009-09-24 18:01:46 -07001086 // Only once we're entirely finished do we indicate our completion
1087 // and release the wakelock
1088 synchronized (mQueueLock) {
1089 mBackupOrRestoreInProgress = false;
1090 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001091
1092 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1093 // This must come after mBackupOrRestoreInProgress is cleared.
1094 backupNow();
1095 }
1096
Dan Egnorbb9001c2009-07-27 12:20:13 -07001097 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001098 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001099 }
1100
Dan Egnor01445162009-09-21 17:04:05 -07001101 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001102 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001103 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001104
Christopher Tate0749dcd2009-08-13 15:13:03 -07001105 // Don't run backup, even if requested, if the target app does not have
1106 // the requisite permission
1107 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1108 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1109 Log.w(TAG, "Skipping backup of unprivileged package "
1110 + request.appInfo.packageName);
1111 continue;
1112 }
1113
Christopher Tate043dadc2009-06-02 16:11:00 -07001114 IBackupAgent agent = null;
1115 int mode = (request.fullBackup)
1116 ? IApplicationThread.BACKUP_MODE_FULL
1117 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1118 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001119 agent = bindToAgentSynchronous(request.appInfo, mode);
1120 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001121 int result = processOneBackup(request, agent, transport);
1122 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001123 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001124 } catch (SecurityException ex) {
1125 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001126 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001127 } finally {
1128 try { // unbind even on timeout, just in case
1129 mActivityManager.unbindBackupAgent(request.appInfo);
1130 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001131 }
1132 }
Dan Egnor01445162009-09-21 17:04:05 -07001133
1134 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001135 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001136
Dan Egnor01445162009-09-21 17:04:05 -07001137 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1138 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001139 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001140 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001141
Dan Egnorbb9001c2009-07-27 12:20:13 -07001142 File savedStateName = new File(mStateDir, packageName);
1143 File backupDataName = new File(mDataDir, packageName + ".data");
1144 File newStateName = new File(mStateDir, packageName + ".new");
1145
1146 ParcelFileDescriptor savedState = null;
1147 ParcelFileDescriptor backupData = null;
1148 ParcelFileDescriptor newState = null;
1149
1150 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001151 try {
1152 // Look up the package info & signatures. This is first so that if it
1153 // throws an exception, there's no file setup yet that would need to
1154 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001155 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1156 // The metadata 'package' is synthetic
1157 packInfo = new PackageInfo();
1158 packInfo.packageName = packageName;
1159 } else {
1160 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001161 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001162 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001163
Christopher Tatec7b31e32009-06-10 15:49:30 -07001164 // In a full backup, we pass a null ParcelFileDescriptor as
1165 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001166 if (!request.fullBackup) {
1167 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001168 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001169 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1170 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001171
Dan Egnorbb9001c2009-07-27 12:20:13 -07001172 backupData = ParcelFileDescriptor.open(backupDataName,
1173 ParcelFileDescriptor.MODE_READ_WRITE |
1174 ParcelFileDescriptor.MODE_CREATE |
1175 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001176
Dan Egnorbb9001c2009-07-27 12:20:13 -07001177 newState = ParcelFileDescriptor.open(newStateName,
1178 ParcelFileDescriptor.MODE_READ_WRITE |
1179 ParcelFileDescriptor.MODE_CREATE |
1180 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001181
1182 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001183 agent.doBackup(savedState, backupData, newState);
1184 logBackupComplete(packageName);
1185 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001186 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001187 Log.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001188 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001189 backupDataName.delete();
1190 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001191 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001192 } finally {
1193 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1194 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1195 try { if (newState != null) newState.close(); } catch (IOException e) {}
1196 savedState = backupData = newState = null;
1197 }
1198
1199 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001200 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001201 try {
1202 int size = (int) backupDataName.length();
1203 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001204 if (result == BackupConstants.TRANSPORT_OK) {
1205 backupData = ParcelFileDescriptor.open(backupDataName,
1206 ParcelFileDescriptor.MODE_READ_ONLY);
1207 result = transport.performBackup(packInfo, backupData);
1208 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001209
Dan Egnor83861e72009-09-17 16:17:55 -07001210 // TODO - We call finishBackup() for each application backed up, because
1211 // we need to know now whether it succeeded or failed. Instead, we should
1212 // hold off on finishBackup() until the end, which implies holding off on
1213 // renaming *all* the output state files (see below) until that happens.
1214
Dan Egnor01445162009-09-21 17:04:05 -07001215 if (result == BackupConstants.TRANSPORT_OK) {
1216 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001217 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001218 } else {
1219 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1220 }
1221
1222 // After successful transport, delete the now-stale data
1223 // and juggle the files so that next time we supply the agent
1224 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001225 if (result == BackupConstants.TRANSPORT_OK) {
1226 backupDataName.delete();
1227 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001228 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001229 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001230 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001231 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001232 } catch (Exception e) {
1233 Log.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001234 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001235 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001236 } finally {
1237 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001238 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001239
Dan Egnor01445162009-09-21 17:04:05 -07001240 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001241 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001242 }
1243
Christopher Tatedf01dea2009-06-09 20:45:02 -07001244
1245 // ----- Restore handling -----
1246
Christopher Tate78dd4a72009-11-04 11:49:08 -08001247 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1248 // If the target resides on the system partition, we allow it to restore
1249 // data from the like-named package in a restore set even if the signatures
1250 // do not match. (Unlike general applications, those flashed to the system
1251 // partition will be signed with the device's platform certificate, so on
1252 // different phones the same system app will have different signatures.)
1253 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1254 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1255 return true;
1256 }
1257
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001258 // Allow unsigned apps, but not signed on one device and unsigned on the other
1259 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001260 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001261 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1262 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001263 if ((storedSigs == null || storedSigs.length == 0)
1264 && (deviceSigs == null || deviceSigs.length == 0)) {
1265 return true;
1266 }
1267 if (storedSigs == null || deviceSigs == null) {
1268 return false;
1269 }
1270
Christopher Tateabce4e82009-06-18 18:35:32 -07001271 // !!! TODO: this demands that every stored signature match one
1272 // that is present on device, and does not demand the converse.
1273 // Is this this right policy?
1274 int nStored = storedSigs.length;
1275 int nDevice = deviceSigs.length;
1276
1277 for (int i=0; i < nStored; i++) {
1278 boolean match = false;
1279 for (int j=0; j < nDevice; j++) {
1280 if (storedSigs[i].equals(deviceSigs[j])) {
1281 match = true;
1282 break;
1283 }
1284 }
1285 if (!match) {
1286 return false;
1287 }
1288 }
1289 return true;
1290 }
1291
Christopher Tatedf01dea2009-06-09 20:45:02 -07001292 class PerformRestoreThread extends Thread {
1293 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001294 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001295 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001296 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001297
Christopher Tate5cbbf562009-06-22 16:44:51 -07001298 class RestoreRequest {
1299 public PackageInfo app;
1300 public int storedAppVersion;
1301
1302 RestoreRequest(PackageInfo _app, int _version) {
1303 app = _app;
1304 storedAppVersion = _version;
1305 }
1306 }
1307
Christopher Tate7d562ec2009-06-25 18:03:43 -07001308 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001309 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001310 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001311 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001312 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001313 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001314
1315 try {
1316 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1317 } catch (RemoteException e) {
1318 // can't happen; the transport is local
1319 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001320 }
1321
1322 @Override
1323 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001324 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001325 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001326 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001327 /**
1328 * Restore sequence:
1329 *
Dan Egnorefe52642009-06-24 00:16:33 -07001330 * 1. get the restore set description for our identity
1331 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001332 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001333 * 3. for each app in the restore queue:
1334 * 3.a. clear the app data
1335 * 3.b. get the restore data for the app from the transport
1336 * 3.c. launch the backup agent for the app
1337 * 3.d. agent.doRestore() with the data from the server
1338 * 3.e. unbind the agent [and kill the app?]
1339 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001340 *
1341 * On errors, we try our best to recover and move on to the next
1342 * application, but if necessary we abort the whole operation --
1343 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001344 */
1345
Christopher Tate7d562ec2009-06-25 18:03:43 -07001346 int error = -1; // assume error
1347
Dan Egnorefe52642009-06-24 00:16:33 -07001348 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001349 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001350 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001351 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001352
Dan Egnorefe52642009-06-24 00:16:33 -07001353 // Get the list of all packages which have backup enabled.
1354 // (Include the Package Manager metadata pseudo-package first.)
1355 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1356 PackageInfo omPackage = new PackageInfo();
1357 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1358 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001359
Dan Egnorefe52642009-06-24 00:16:33 -07001360 List<PackageInfo> agentPackages = allAgentPackages();
1361 restorePackages.addAll(agentPackages);
1362
Christopher Tate7d562ec2009-06-25 18:03:43 -07001363 // let the observer know that we're running
1364 if (mObserver != null) {
1365 try {
1366 // !!! TODO: get an actual count from the transport after
1367 // its startRestore() runs?
1368 mObserver.restoreStarting(restorePackages.size());
1369 } catch (RemoteException e) {
1370 Log.d(TAG, "Restore observer died at restoreStarting");
1371 mObserver = null;
1372 }
1373 }
1374
Dan Egnor01445162009-09-21 17:04:05 -07001375 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1376 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001377 Log.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001378 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001379 return;
1380 }
1381
1382 String packageName = mTransport.nextRestorePackage();
1383 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001384 Log.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001385 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001386 return;
1387 } else if (packageName.equals("")) {
1388 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001389 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001390 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001391 return;
1392 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1393 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1394 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001395 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001396 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001397 return;
1398 }
1399
1400 // Pull the Package Manager metadata from the restore set first
1401 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1402 mPackageManager, agentPackages);
1403 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1404
Christopher Tate8c032472009-07-02 14:28:47 -07001405 // Verify that the backup set includes metadata. If not, we can't do
1406 // signature/version verification etc, so we simply do not proceed with
1407 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001408 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001409 Log.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001410 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001411 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001412 return;
1413 }
1414
Christopher Tate7d562ec2009-06-25 18:03:43 -07001415 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001416 for (;;) {
1417 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001418
Dan Egnorefe52642009-06-24 00:16:33 -07001419 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001420 Log.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001421 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001422 return;
1423 } else if (packageName.equals("")) {
1424 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001425 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001426
Christopher Tate7d562ec2009-06-25 18:03:43 -07001427 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001428 try {
1429 mObserver.onUpdate(count);
1430 } catch (RemoteException e) {
1431 Log.d(TAG, "Restore observer died in onUpdate");
1432 mObserver = null;
1433 }
1434 }
1435
Dan Egnorefe52642009-06-24 00:16:33 -07001436 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1437 if (metaInfo == null) {
1438 Log.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001439 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001440 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001441 continue;
1442 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001443
Dan Egnorbb9001c2009-07-27 12:20:13 -07001444 PackageInfo packageInfo;
1445 try {
1446 int flags = PackageManager.GET_SIGNATURES;
1447 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1448 } catch (NameNotFoundException e) {
1449 Log.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001450 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001451 "Package missing on device");
1452 continue;
1453 }
1454
Dan Egnorefe52642009-06-24 00:16:33 -07001455 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001456 String message = "Version " + metaInfo.versionCode
1457 + " > installed version " + packageInfo.versionCode;
1458 Log.w(TAG, "Package " + packageName + ": " + message);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001459 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001460 continue;
1461 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001462
Christopher Tate78dd4a72009-11-04 11:49:08 -08001463 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001464 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001465 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001466 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001467 continue;
1468 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001469
Dan Egnorefe52642009-06-24 00:16:33 -07001470 if (DEBUG) Log.v(TAG, "Package " + packageName
1471 + " restore version [" + metaInfo.versionCode
1472 + "] is compatible with installed version ["
1473 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001474
Christopher Tate5e1ab332009-09-01 20:32:49 -07001475 // Now perform the actual restore: first clear the app's data
1476 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001477 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001478
1479 // Then set up and bind the agent (with a restricted Application object
1480 // unless the application says otherwise)
1481 boolean useRealApp = (packageInfo.applicationInfo.flags
1482 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1483 if (DEBUG && useRealApp) {
1484 Log.v(TAG, "agent requires real Application subclass for restore");
1485 }
Dan Egnorefe52642009-06-24 00:16:33 -07001486 IBackupAgent agent = bindToAgentSynchronous(
1487 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001488 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1489 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001490 if (agent == null) {
1491 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001492 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001493 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001494 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001495 }
1496
Christopher Tate5e1ab332009-09-01 20:32:49 -07001497 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001498 try {
1499 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001500 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001501 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001502 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001503 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001504
1505 // The agent was probably running with a stub Application object,
1506 // which isn't a valid run mode for the main app logic. Shut
1507 // down the app so that next time it's launched, it gets the
1508 // usual full initialization.
1509 if ((packageInfo.applicationInfo.flags
1510 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1511 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1512 + packageInfo.applicationInfo.processName);
1513 mActivityManager.killApplicationProcess(
1514 packageInfo.applicationInfo.processName,
1515 packageInfo.applicationInfo.uid);
1516 }
Dan Egnorefe52642009-06-24 00:16:33 -07001517 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001518 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001519
1520 // if we get this far, report success to the observer
1521 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001522 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001523 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001524 } catch (Exception e) {
1525 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001526 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001527 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1528
Dan Egnorefe52642009-06-24 00:16:33 -07001529 try {
1530 mTransport.finishRestore();
1531 } catch (RemoteException e) {
1532 Log.e(TAG, "Error finishing restore", e);
1533 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001534
1535 if (mObserver != null) {
1536 try {
1537 mObserver.restoreFinished(error);
1538 } catch (RemoteException e) {
1539 Log.d(TAG, "Restore observer died at restoreFinished");
1540 }
1541 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001542
1543 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001544 synchronized (mQueueLock) {
1545 mBackupOrRestoreInProgress = false;
1546 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001547 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001548 }
1549 }
1550
Dan Egnorefe52642009-06-24 00:16:33 -07001551 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1552 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001553 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001554 final String packageName = app.packageName;
1555
Dan Egnorbb9001c2009-07-27 12:20:13 -07001556 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001557
Christopher Tate0749dcd2009-08-13 15:13:03 -07001558 // Don't restore to unprivileged packages
1559 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1560 packageName) != PackageManager.PERMISSION_GRANTED) {
1561 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1562 }
1563
Christopher Tatec7b31e32009-06-10 15:49:30 -07001564 // !!! TODO: get the dirs from the transport
1565 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001566 File newStateName = new File(mStateDir, packageName + ".new");
1567 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001568
Dan Egnorbb9001c2009-07-27 12:20:13 -07001569 ParcelFileDescriptor backupData = null;
1570 ParcelFileDescriptor newState = null;
1571
1572 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001573 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001574 backupData = ParcelFileDescriptor.open(backupDataName,
1575 ParcelFileDescriptor.MODE_READ_WRITE |
1576 ParcelFileDescriptor.MODE_CREATE |
1577 ParcelFileDescriptor.MODE_TRUNCATE);
1578
Dan Egnor01445162009-09-21 17:04:05 -07001579 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001580 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001581 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001582 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001583 }
1584
1585 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001586 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001587 backupData = ParcelFileDescriptor.open(backupDataName,
1588 ParcelFileDescriptor.MODE_READ_ONLY);
1589
Dan Egnorbb9001c2009-07-27 12:20:13 -07001590 newState = ParcelFileDescriptor.open(newStateName,
1591 ParcelFileDescriptor.MODE_READ_WRITE |
1592 ParcelFileDescriptor.MODE_CREATE |
1593 ParcelFileDescriptor.MODE_TRUNCATE);
1594
1595 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001596
1597 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001598 //
1599 // !!! TODO: the restored data should be migrated on the server
1600 // side into the current dataset. In that case the new state file
1601 // we just created would reflect the data already extant in the
1602 // backend, so there'd be nothing more to do. Until that happens,
1603 // however, we need to make sure that we record the data to the
1604 // current backend dataset. (Yes, this means shipping the data over
1605 // the wire in both directions. That's bad, but consistency comes
1606 // first, then efficiency.) Once we introduce server-side data
1607 // migration to the newly-restored device's dataset, we will change
1608 // the following from a discard of the newly-written state to the
1609 // "correct" operation of renaming into the canonical state blob.
1610 newStateName.delete(); // TODO: remove; see above comment
1611 //newStateName.renameTo(savedStateName); // TODO: replace with this
1612
Dan Egnorbb9001c2009-07-27 12:20:13 -07001613 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001614 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001615 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001616 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001617 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001618
Christopher Tate96733042009-07-20 14:49:13 -07001619 // If the agent fails restore, it might have put the app's data
1620 // into an incoherent state. For consistency we wipe its data
1621 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001622 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001623 } finally {
1624 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001625 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1626 try { if (newState != null) newState.close(); } catch (IOException e) {}
1627 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001628 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001629 }
1630 }
1631
Christopher Tateee0e78a2009-07-02 11:17:03 -07001632 class PerformClearThread extends Thread {
1633 IBackupTransport mTransport;
1634 PackageInfo mPackage;
1635
1636 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1637 mTransport = transport;
1638 mPackage = packageInfo;
1639 }
1640
1641 @Override
1642 public void run() {
1643 try {
1644 // Clear the on-device backup state to ensure a full backup next time
1645 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1646 File stateFile = new File(stateDir, mPackage.packageName);
1647 stateFile.delete();
1648
1649 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001650 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001651 mTransport.clearBackupData(mPackage);
1652 } catch (RemoteException e) {
1653 // can't happen; the transport is local
1654 } finally {
1655 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001656 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001657 mTransport.finishBackup();
1658 } catch (RemoteException e) {
1659 // can't happen; the transport is local
1660 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001661
1662 // Last but not least, release the cpu
Christopher Tatea253f162009-09-27 15:16:44 -07001663 synchronized (mQueueLock) {
1664 mBackupOrRestoreInProgress = false;
1665 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001666 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001667 }
1668 }
1669 }
1670
Christopher Tate4cc86e12009-09-21 19:36:51 -07001671 class PerformInitializeThread extends Thread {
1672 HashSet<String> mQueue;
1673
1674 PerformInitializeThread(HashSet<String> transportNames) {
1675 mQueue = transportNames;
1676 }
1677
1678 @Override
1679 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001680 try {
1681 for (String transportName : mQueue) {
1682 IBackupTransport transport = getTransport(transportName);
1683 if (transport == null) {
1684 Log.e(TAG, "Requested init for " + transportName + " but not found");
1685 continue;
1686 }
1687
Dan Egnor726247c2009-09-29 19:12:31 -07001688 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001689 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001690 long startRealtime = SystemClock.elapsedRealtime();
1691 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001692
Christopher Tate4cc86e12009-09-21 19:36:51 -07001693 if (status == BackupConstants.TRANSPORT_OK) {
1694 status = transport.finishBackup();
1695 }
1696
1697 // Okay, the wipe really happened. Clean up our local bookkeeping.
1698 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001699 Log.i(TAG, "Device init successful");
1700 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001701 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001702 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001703 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001704 synchronized (mQueueLock) {
1705 recordInitPendingLocked(false, transportName);
1706 }
Dan Egnor726247c2009-09-29 19:12:31 -07001707 } else {
1708 // If this didn't work, requeue this one and try again
1709 // after a suitable interval
1710 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001711 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001712 synchronized (mQueueLock) {
1713 recordInitPendingLocked(true, transportName);
1714 }
1715 // do this via another alarm to make sure of the wakelock states
1716 long delay = transport.requestBackupTime();
1717 if (DEBUG) Log.w(TAG, "init failed on "
1718 + transportName + " resched in " + delay);
1719 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1720 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001721 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001722 }
1723 } catch (RemoteException e) {
1724 // can't happen; the transports are local
1725 } catch (Exception e) {
1726 Log.e(TAG, "Unexpected error performing init", e);
1727 } finally {
1728 // Done; indicate that we're finished and release the wakelock
1729 synchronized (mQueueLock) {
1730 mInitInProgress = false;
1731 }
1732 mWakelock.release();
1733 }
1734 }
1735 }
1736
Christopher Tatedf01dea2009-06-09 20:45:02 -07001737
Christopher Tate487529a2009-04-29 14:03:25 -07001738 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001739
Dan Egnor852f8e42009-09-30 11:20:45 -07001740 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001741 // Record that we need a backup pass for the caller. Since multiple callers
1742 // may share a uid, we need to note all candidates within that uid and schedule
1743 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001744 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001745
Christopher Tate63d27002009-06-16 17:16:42 -07001746 // If the caller does not hold the BACKUP permission, it can only request a
1747 // backup of its own data.
1748 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001749 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001750 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1751 targets = mBackupParticipants.get(Binder.getCallingUid());
1752 } else {
1753 // a caller with full permission can ask to back up any participating app
1754 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001755 targets = new HashSet<ApplicationInfo>();
1756 int N = mBackupParticipants.size();
1757 for (int i = 0; i < N; i++) {
1758 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1759 if (s != null) {
1760 targets.addAll(s);
1761 }
1762 }
1763 }
Christopher Tate487529a2009-04-29 14:03:25 -07001764 if (targets != null) {
1765 synchronized (mQueueLock) {
1766 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001767 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001768 // validate the caller-supplied package name against the known set of
1769 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001770 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001771 // Add the caller to the set of pending backups. If there is
1772 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001773 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001774 if (mPendingBackups.put(app, req) == null) {
1775 // Journal this request in case of crash. The put()
1776 // operation returned null when this package was not already
1777 // in the set; we want to avoid touching the disk redundantly.
1778 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001779
Christopher Tate22b60d82009-07-07 16:36:02 -07001780 if (DEBUG) {
1781 int numKeys = mPendingBackups.size();
1782 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1783 for (BackupRequest b : mPendingBackups.values()) {
1784 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1785 }
1786 }
1787 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001788 }
1789 }
Christopher Tate487529a2009-04-29 14:03:25 -07001790 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001791 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001792 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1793 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001794 }
1795 }
Christopher Tate46758122009-05-06 11:22:00 -07001796
Christopher Tatecde87f42009-06-12 12:55:53 -07001797 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001798 RandomAccessFile out = null;
1799 try {
1800 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1801 out = new RandomAccessFile(mJournal, "rws");
1802 out.seek(out.length());
1803 out.writeUTF(str);
1804 } catch (IOException e) {
1805 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1806 mJournal = null;
1807 } finally {
1808 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001809 }
1810 }
1811
Christopher Tateee0e78a2009-07-02 11:17:03 -07001812 // Clear the given package's backup data from the current transport
1813 public void clearBackupData(String packageName) {
1814 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1815 PackageInfo info;
1816 try {
1817 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1818 } catch (NameNotFoundException e) {
1819 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1820 return;
1821 }
1822
1823 // If the caller does not hold the BACKUP permission, it can only request a
1824 // wipe of its own backed-up data.
1825 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001826 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001827 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1828 apps = mBackupParticipants.get(Binder.getCallingUid());
1829 } else {
1830 // a caller with full permission can ask to back up any participating app
1831 // !!! TODO: allow data-clear of ANY app?
1832 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1833 apps = new HashSet<ApplicationInfo>();
1834 int N = mBackupParticipants.size();
1835 for (int i = 0; i < N; i++) {
1836 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1837 if (s != null) {
1838 apps.addAll(s);
1839 }
1840 }
1841 }
1842
1843 // now find the given package in the set of candidate apps
1844 for (ApplicationInfo app : apps) {
1845 if (app.packageName.equals(packageName)) {
1846 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1847 // found it; fire off the clear request
1848 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001849 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001850 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001851 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1852 new ClearParams(getTransport(mCurrentTransport), info));
1853 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001854 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001855 }
1856 break;
1857 }
1858 }
1859 }
1860
Christopher Tateace7f092009-06-15 18:07:25 -07001861 // Run a backup pass immediately for any applications that have declared
1862 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07001863 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04001864 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001865
Christopher Tateace7f092009-06-15 18:07:25 -07001866 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001867 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001868 // Because the alarms we are using can jitter, and we want an *immediate*
1869 // backup pass to happen, we restart the timer beginning with "next time,"
1870 // then manually fire the backup trigger intent ourselves.
1871 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001872 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001873 mRunBackupIntent.send();
1874 } catch (PendingIntent.CanceledException e) {
1875 // should never happen
1876 Log.e(TAG, "run-backup intent cancelled!");
1877 }
Christopher Tate46758122009-05-06 11:22:00 -07001878 }
1879 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001880
Christopher Tate8031a3d2009-07-06 16:36:05 -07001881 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001882 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001883 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1884 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001885
Christopher Tate4cc86e12009-09-21 19:36:51 -07001886 Log.i(TAG, "Backup enabled => " + enable);
1887
Christopher Tate6ef58a12009-06-29 14:56:28 -07001888 boolean wasEnabled = mEnabled;
1889 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001890 Settings.Secure.putInt(mContext.getContentResolver(),
1891 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001892 mEnabled = enable;
1893 }
1894
Christopher Tate49401dd2009-07-01 12:34:29 -07001895 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001896 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001897 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001898 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001899 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001900 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001901 if (DEBUG) Log.i(TAG, "Opting out of backup");
1902
Christopher Tateb6787f22009-07-02 17:40:45 -07001903 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001904
1905 // This also constitutes an opt-out, so we wipe any data for
1906 // this device from the backend. We start that process with
1907 // an alarm in order to guarantee wakelock states.
1908 if (wasEnabled && mProvisioned) {
1909 // NOTE: we currently flush every registered transport, not just
1910 // the currently-active one.
1911 HashSet<String> allTransports;
1912 synchronized (mTransports) {
1913 allTransports = new HashSet<String>(mTransports.keySet());
1914 }
1915 // build the set of transports for which we are posting an init
1916 for (String transport : allTransports) {
1917 recordInitPendingLocked(true, transport);
1918 }
1919 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1920 mRunInitIntent);
1921 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001922 }
1923 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001924 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001925
Christopher Tate8031a3d2009-07-06 16:36:05 -07001926 // Mark the backup service as having been provisioned
1927 public void setBackupProvisioned(boolean available) {
1928 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1929 "setBackupProvisioned");
1930
1931 boolean wasProvisioned = mProvisioned;
1932 synchronized (this) {
1933 Settings.Secure.putInt(mContext.getContentResolver(),
1934 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1935 mProvisioned = available;
1936 }
1937
1938 synchronized (mQueueLock) {
1939 if (available && !wasProvisioned && mEnabled) {
1940 // we're now good to go, so start the backup alarms
1941 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1942 } else if (!available) {
1943 // No longer enabled, so stop running backups
1944 Log.w(TAG, "Backup service no longer provisioned");
1945 mAlarmManager.cancel(mRunBackupIntent);
1946 }
1947 }
1948 }
1949
1950 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07001951 // We used to use setInexactRepeating(), but that may be linked to
1952 // backups running at :00 more often than not, creating load spikes.
1953 // Schedule at an exact time for now, and also add a bit of "fuzz".
1954
1955 Random random = new Random();
1956 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
1957 random.nextInt(FUZZ_MILLIS);
1958 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
1959 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07001960 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07001961 }
1962
Christopher Tate6ef58a12009-06-29 14:56:28 -07001963 // Report whether the backup mechanism is currently enabled
1964 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001965 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001966 return mEnabled; // no need to synchronize just to read it
1967 }
1968
Christopher Tate91717492009-06-26 21:07:13 -07001969 // Report the name of the currently active transport
1970 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001971 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001972 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001973 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001974 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001975 }
1976
Christopher Tate91717492009-06-26 21:07:13 -07001977 // Report all known, available backup transports
1978 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001979 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001980
Christopher Tate91717492009-06-26 21:07:13 -07001981 String[] list = null;
1982 ArrayList<String> known = new ArrayList<String>();
1983 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1984 if (entry.getValue() != null) {
1985 known.add(entry.getKey());
1986 }
1987 }
1988
1989 if (known.size() > 0) {
1990 list = new String[known.size()];
1991 known.toArray(list);
1992 }
1993 return list;
1994 }
1995
1996 // Select which transport to use for the next backup operation. If the given
1997 // name is not one of the available transports, no action is taken and the method
1998 // returns null.
1999 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002001
2002 synchronized (mTransports) {
2003 String prevTransport = null;
2004 if (mTransports.get(transport) != null) {
2005 prevTransport = mCurrentTransport;
2006 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002007 Settings.Secure.putString(mContext.getContentResolver(),
2008 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002009 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2010 + " returning " + prevTransport);
2011 } else {
2012 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2013 }
2014 return prevTransport;
2015 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002016 }
2017
2018 // Callback: a requested backup agent has been instantiated. This should only
2019 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002020 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002021 synchronized(mAgentConnectLock) {
2022 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2023 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2024 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2025 mConnectedAgent = agent;
2026 mConnecting = false;
2027 } else {
2028 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2029 + " claiming agent connected");
2030 }
2031 mAgentConnectLock.notifyAll();
2032 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002033 }
2034
2035 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2036 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002037 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002038 public void agentDisconnected(String packageName) {
2039 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002040 synchronized(mAgentConnectLock) {
2041 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2042 mConnectedAgent = null;
2043 mConnecting = false;
2044 } else {
2045 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2046 + " claiming agent disconnected");
2047 }
2048 mAgentConnectLock.notifyAll();
2049 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002050 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002051
Christopher Tate8c850b72009-06-07 19:33:20 -07002052 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002053 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002054 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002055
2056 synchronized(this) {
2057 if (mActiveRestoreSession != null) {
2058 Log.d(TAG, "Restore session requested but one already active");
2059 return null;
2060 }
Christopher Tate91717492009-06-26 21:07:13 -07002061 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002062 }
2063 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002064 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002065
Christopher Tate9b3905c2009-06-08 15:24:01 -07002066 // ----- Restore session -----
2067
2068 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002069 private static final String TAG = "RestoreSession";
2070
Christopher Tate9b3905c2009-06-08 15:24:01 -07002071 private IBackupTransport mRestoreTransport = null;
2072 RestoreSet[] mRestoreSets = null;
2073
Christopher Tate91717492009-06-26 21:07:13 -07002074 RestoreSession(String transport) {
2075 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002076 }
2077
2078 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002079 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002080 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002081 "getAvailableRestoreSets");
2082
Christopher Tatef68eb502009-06-16 11:02:01 -07002083 try {
Christopher Tate43383042009-07-13 15:17:13 -07002084 if (mRestoreTransport == null) {
2085 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002086 return null;
2087 }
2088 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002089 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002090 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002091 }
2092 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002093 } catch (Exception e) {
2094 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2095 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002096 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002097 }
2098
Dan Egnor0084da52009-07-29 12:57:16 -07002099 public synchronized int performRestore(long token, IRestoreObserver observer) {
2100 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2101 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002102
Christopher Tatef2c321a2009-08-10 15:43:36 -07002103 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2104 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002105
Dan Egnor0084da52009-07-29 12:57:16 -07002106 if (mRestoreTransport == null || mRestoreSets == null) {
2107 Log.e(TAG, "Ignoring performRestore() with no restore set");
2108 return -1;
2109 }
2110
Christopher Tate21ab6a52009-09-24 18:01:46 -07002111 synchronized (mQueueLock) {
2112 if (mBackupOrRestoreInProgress) {
2113 Log.e(TAG, "Backup pass in progress, restore aborted");
2114 return -1;
2115 }
2116
2117 for (int i = 0; i < mRestoreSets.length; i++) {
2118 if (token == mRestoreSets[i].token) {
2119 long oldId = Binder.clearCallingIdentity();
2120 // Suppress backups until the restore operation is finished
2121 mBackupOrRestoreInProgress = true;
2122 mWakelock.acquire();
2123 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2124 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2125 mBackupHandler.sendMessage(msg);
2126 Binder.restoreCallingIdentity(oldId);
2127 return 0;
2128 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002129 }
2130 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002131
2132 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002133 return -1;
2134 }
2135
Dan Egnor0084da52009-07-29 12:57:16 -07002136 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002137 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002138 "endRestoreSession");
2139
Dan Egnor0084da52009-07-29 12:57:16 -07002140 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002141
Dan Egnor0084da52009-07-29 12:57:16 -07002142 synchronized (this) {
2143 try {
2144 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2145 } catch (Exception e) {
2146 Log.e(TAG, "Error in finishRestore", e);
2147 } finally {
2148 mRestoreTransport = null;
2149 }
2150 }
2151
2152 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002153 if (BackupManagerService.this.mActiveRestoreSession == this) {
2154 BackupManagerService.this.mActiveRestoreSession = null;
2155 } else {
2156 Log.e(TAG, "ending non-current restore session");
2157 }
2158 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002159 }
2160 }
2161
Christopher Tate043dadc2009-06-02 16:11:00 -07002162
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002163 @Override
2164 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2165 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002166 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002167 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
2168 + (!mBackupOrRestoreInProgress ? "not " : "") + "in progress / "
2169 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init / "
2170 + (!mInitInProgress ? "not " : "") + "initializing");
2171 pw.println("Last backup pass: " + mLastBackupPass
2172 + " (now = " + System.currentTimeMillis() + ')');
2173 pw.println(" next scheduled: " + mNextBackupPass);
2174
Christopher Tate91717492009-06-26 21:07:13 -07002175 pw.println("Available transports:");
2176 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002177 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2178 try {
2179 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2180 for (File f : dir.listFiles()) {
2181 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2182 }
2183 } catch (RemoteException e) {
2184 Log.e(TAG, "Error in transportDirName()", e);
2185 pw.println(" Error: " + e);
2186 }
Christopher Tate91717492009-06-26 21:07:13 -07002187 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002188
2189 pw.println("Pending init: " + mPendingInits.size());
2190 for (String s : mPendingInits) {
2191 pw.println(" " + s);
2192 }
2193
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002194 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002195 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002196 for (int i=0; i<N; i++) {
2197 int uid = mBackupParticipants.keyAt(i);
2198 pw.print(" uid: ");
2199 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002200 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2201 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002202 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002203 }
2204 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002205
Christopher Tate73e02522009-07-15 14:18:26 -07002206 pw.println("Ever backed up: " + mEverStoredApps.size());
2207 for (String pkg : mEverStoredApps) {
2208 pw.println(" " + pkg);
2209 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002210
2211 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002212 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002213 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002214 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002215 }
2216 }
Christopher Tate487529a2009-04-29 14:03:25 -07002217}