blob: 2e4551268a08d5f28be2ea7fd33fe028d31f1f6c [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;
Oscar Montemayora8529f62009-11-18 10:14:20 -080025import android.backup.IBackupManager;
26import android.backup.IRestoreObserver;
27import android.backup.IRestoreSession;
28import android.backup.RestoreSet;
Christopher Tate3799bc22009-05-06 16:13:56 -070029import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070030import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070031import android.content.Context;
32import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070033import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070034import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070035import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070036import android.content.pm.IPackageDataObserver;
Christopher Tate7b881282009-06-07 13:52:37 -070037import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070038import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070039import android.content.pm.Signature;
Oscar Montemayora8529f62009-11-18 10:14:20 -080040import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070041import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070042import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070043import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070044import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070045import android.os.Handler;
46import android.os.IBinder;
47import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070048import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070049import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070050import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070052import android.os.SystemClock;
Oscar Montemayora8529f62009-11-18 10:14:20 -080053import android.os.SystemProperties;
54import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070055import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070056import android.util.Log;
57import android.util.SparseArray;
58
Christopher Tated55e18a2009-09-21 10:12:59 -070059import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070060import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080061import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070062import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070063
Christopher Tatecde87f42009-06-12 12:55:53 -070064import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070065import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070066import java.io.FileDescriptor;
Christopher Tate4cc86e12009-09-21 19:36:51 -070067import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070068import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070069import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070070import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040071import java.util.ArrayList;
72import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070073import java.util.HashSet;
74import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070075import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070076import java.util.Random;
Christopher Tate487529a2009-04-29 14:03:25 -070077
78class BackupManagerService extends IBackupManager.Stub {
79 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070080 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070081
Christopher Tate49401dd2009-07-01 12:34:29 -070082 // How often we perform a backup pass. Privileged external callers can
83 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070084 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070085
Dan Egnorc1c49c02009-10-30 17:35:39 -070086 // Random variation in backup scheduling time to avoid server load spikes
87 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
88
Christopher Tate8031a3d2009-07-06 16:36:05 -070089 // The amount of time between the initial provisioning of the device and
90 // the first backup pass.
91 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
92
Christopher Tate4cc86e12009-09-21 19:36:51 -070093 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
94 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
95 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070096 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070097 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -070098 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -070099 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700100 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700101
102 // Timeout interval for deciding that a bind or clear-data has taken too long
103 static final long TIMEOUT_INTERVAL = 10 * 1000;
104
Christopher Tate487529a2009-04-29 14:03:25 -0700105 private Context mContext;
106 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700107 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700108 private PowerManager mPowerManager;
109 private AlarmManager mAlarmManager;
110
Christopher Tate73e02522009-07-15 14:18:26 -0700111 boolean mEnabled; // access to this is synchronized on 'this'
112 boolean mProvisioned;
113 PowerManager.WakeLock mWakelock;
114 final BackupHandler mBackupHandler = new BackupHandler();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700115 PendingIntent mRunBackupIntent, mRunInitIntent;
116 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700117 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700118 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700119 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700120 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700121 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700122 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700123 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700124
Christopher Tate181fafa2009-05-14 11:12:14 -0700125 BackupRequest(ApplicationInfo app, boolean isFull) {
126 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700127 fullBackup = isFull;
128 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700129
130 public String toString() {
131 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
132 }
Christopher Tate46758122009-05-06 11:22:00 -0700133 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400134 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700135 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700136 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700137
138 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700139 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700140
141 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700142 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700143
Christopher Tate043dadc2009-06-02 16:11:00 -0700144 // The thread performing the sequence of queued backups binds to each app's agent
145 // in succession. Bind notifications are asynchronously delivered through the
146 // Activity Manager; use this lock object to signal when a requested binding has
147 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700148 final Object mAgentConnectLock = new Object();
149 IBackupAgent mConnectedAgent;
150 volatile boolean mConnecting;
Christopher Tate21ab6a52009-09-24 18:01:46 -0700151 volatile boolean mBackupOrRestoreInProgress = false;
Christopher Tate55f931a2009-09-29 17:17:34 -0700152 volatile long mLastBackupPass;
153 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700154
Christopher Tate55f931a2009-09-29 17:17:34 -0700155 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700156 final Object mClearDataLock = new Object();
157 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700158
Christopher Tate91717492009-06-26 21:07:13 -0700159 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700160 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700161 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700162 String mCurrentTransport;
163 IBackupTransport mLocalTransport, mGoogleTransport;
164 RestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700165
Christopher Tate73e02522009-07-15 14:18:26 -0700166 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700167 public IBackupTransport transport;
168 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700169 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700170
Dan Egnor156411d2009-06-26 13:20:02 -0700171 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700172 transport = _transport;
173 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700174 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700175 }
176 }
177
Christopher Tate73e02522009-07-15 14:18:26 -0700178 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700179 public IBackupTransport transport;
180 public PackageInfo packageInfo;
181
182 ClearParams(IBackupTransport _transport, PackageInfo _info) {
183 transport = _transport;
184 packageInfo = _info;
185 }
186 }
187
Christopher Tate5cb400b2009-06-25 16:03:14 -0700188 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700189 File mBaseStateDir;
190 File mDataDir;
191 File mJournalDir;
192 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700193
194 // Keep a log of all the apps we've ever backed up
195 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700196 HashSet<String> mEverStoredApps = new HashSet<String>();
197
Christopher Tate4cc86e12009-09-21 19:36:51 -0700198 // Persistently track the need to do a full init
199 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
200 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tate21ab6a52009-09-24 18:01:46 -0700201 volatile boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700202
Christopher Tate487529a2009-04-29 14:03:25 -0700203 public BackupManagerService(Context context) {
204 mContext = context;
205 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700206 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700207
Christopher Tateb6787f22009-07-02 17:40:45 -0700208 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
209 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
210
Christopher Tate22b87872009-05-04 16:41:53 -0700211 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700212 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700213 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700214 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700215 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800216 // If Encrypted file systems is enabled or disabled, this call will return the
217 // correct directory.
218 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
219 mBaseStateDir.mkdirs();
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 Tatedfa47b56e2009-12-22 16:01:32 -0800500 // Add a transport to our set of available backends. If 'transport' is null, this
501 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700502 private void registerTransport(String name, IBackupTransport transport) {
503 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700504 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800505 if (transport != null) {
506 mTransports.put(name, transport);
507 } else {
508 mTransports.remove(name);
509 if (mCurrentTransport.equals(name)) {
510 mCurrentTransport = null;
511 }
512 // Nothing further to do in the unregistration case
513 return;
514 }
Christopher Tate91717492009-06-26 21:07:13 -0700515 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700516
517 // If the init sentinel file exists, we need to be sure to perform the init
518 // as soon as practical. We also create the state directory at registration
519 // time to ensure it's present from the outset.
520 try {
521 String transportName = transport.transportDirName();
522 File stateDir = new File(mBaseStateDir, transportName);
523 stateDir.mkdirs();
524
525 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
526 if (initSentinel.exists()) {
527 synchronized (mQueueLock) {
528 mPendingInits.add(transportName);
529
530 // TODO: pick a better starting time than now + 1 minute
531 long delay = 1000 * 60; // one minute, in milliseconds
532 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
533 System.currentTimeMillis() + delay, mRunInitIntent);
534 }
535 }
536 } catch (RemoteException e) {
537 // can't happen, the transport is local
538 }
Christopher Tate91717492009-06-26 21:07:13 -0700539 }
540
Christopher Tate3799bc22009-05-06 16:13:56 -0700541 // ----- Track installation/removal of packages -----
542 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
543 public void onReceive(Context context, Intent intent) {
544 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
545
546 Uri uri = intent.getData();
547 if (uri == null) {
548 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700549 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700550 String pkgName = uri.getSchemeSpecificPart();
551 if (pkgName == null) {
552 return;
553 }
554
555 String action = intent.getAction();
556 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
557 synchronized (mBackupParticipants) {
558 Bundle extras = intent.getExtras();
559 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
560 // The package was just upgraded
561 updatePackageParticipantsLocked(pkgName);
562 } else {
563 // The package was just added
564 addPackageParticipantsLocked(pkgName);
565 }
566 }
567 }
568 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
569 Bundle extras = intent.getExtras();
570 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
571 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
572 } else {
573 synchronized (mBackupParticipants) {
574 removePackageParticipantsLocked(pkgName);
575 }
576 }
577 }
578 }
579 };
580
Dan Egnor87a02bc2009-06-17 02:30:10 -0700581 // ----- Track connection to GoogleBackupTransport service -----
582 ServiceConnection mGoogleConnection = new ServiceConnection() {
583 public void onServiceConnected(ComponentName name, IBinder service) {
584 if (DEBUG) Log.v(TAG, "Connected to Google transport");
585 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700586 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700587 }
588
589 public void onServiceDisconnected(ComponentName name) {
590 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
591 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700592 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700593 }
594 };
595
Joe Onorato8ad02812009-05-13 01:41:44 -0400596 // ----- Run the actual backup process asynchronously -----
597
Christopher Tate181fafa2009-05-14 11:12:14 -0700598 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400599 public void handleMessage(Message msg) {
600
601 switch (msg.what) {
602 case MSG_RUN_BACKUP:
Dan Egnor87a02bc2009-06-17 02:30:10 -0700603 {
Christopher Tate55f931a2009-09-29 17:17:34 -0700604 mLastBackupPass = System.currentTimeMillis();
605 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
606
Christopher Tate91717492009-06-26 21:07:13 -0700607 IBackupTransport transport = getTransport(mCurrentTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700608 if (transport == null) {
609 Log.v(TAG, "Backup requested but no transport available");
Christopher Tatea253f162009-09-27 15:16:44 -0700610 synchronized (mQueueLock) {
611 mBackupOrRestoreInProgress = false;
612 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700613 mWakelock.release();
Dan Egnor87a02bc2009-06-17 02:30:10 -0700614 break;
615 }
616
Joe Onorato8ad02812009-05-13 01:41:44 -0400617 // snapshot the pending-backup set and work on that
Christopher Tate6aa41f42009-06-19 14:14:22 -0700618 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400619 synchronized (mQueueLock) {
Christopher Tate49401dd2009-07-01 12:34:29 -0700620 // Do we have any work to do?
621 if (mPendingBackups.size() > 0) {
622 for (BackupRequest b: mPendingBackups.values()) {
623 queue.add(b);
Christopher Tatecde87f42009-06-12 12:55:53 -0700624 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700625 Log.v(TAG, "clearing pending backups");
626 mPendingBackups.clear();
Christopher Tatecde87f42009-06-12 12:55:53 -0700627
Christopher Tate49401dd2009-07-01 12:34:29 -0700628 // Start a new backup-queue journal file too
Dan Egnor852f8e42009-09-30 11:20:45 -0700629 File oldJournal = mJournal;
630 mJournal = null;
Christopher Tate49401dd2009-07-01 12:34:29 -0700631
632 // At this point, we have started a new journal file, and the old
633 // file identity is being passed to the backup processing thread.
634 // When it completes successfully, that old journal file will be
635 // deleted. If we crash prior to that, the old journal is parsed
636 // at next boot and the journaled requests fulfilled.
637 (new PerformBackupThread(transport, queue, oldJournal)).start();
638 } else {
639 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tatea253f162009-09-27 15:16:44 -0700640 synchronized (mQueueLock) {
641 mBackupOrRestoreInProgress = false;
642 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700643 mWakelock.release();
Christopher Tate49401dd2009-07-01 12:34:29 -0700644 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400645 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700646 break;
Dan Egnor87a02bc2009-06-17 02:30:10 -0700647 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700648
649 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400650 break;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700651
652 case MSG_RUN_RESTORE:
653 {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700654 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400655 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tateb6787f22009-07-02 17:40:45 -0700656 (new PerformRestoreThread(params.transport, params.observer,
657 params.token)).start();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700658 break;
659 }
Christopher Tateee0e78a2009-07-02 11:17:03 -0700660
661 case MSG_RUN_CLEAR:
662 {
663 ClearParams params = (ClearParams)msg.obj;
664 (new PerformClearThread(params.transport, params.packageInfo)).start();
665 break;
666 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700667
668 case MSG_RUN_INITIALIZE:
669 {
670 HashSet<String> queue;
671
672 // Snapshot the pending-init queue and work on that
673 synchronized (mQueueLock) {
674 queue = new HashSet<String>(mPendingInits);
675 mPendingInits.clear();
676 }
677
678 (new PerformInitializeThread(queue)).start();
679 break;
680 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400681 }
682 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400683 }
684
Christopher Tate181fafa2009-05-14 11:12:14 -0700685 // Add the backup agents in the given package to our set of known backup participants.
686 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700687 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700688 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700689 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700690 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700691 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700692 }
693
Christopher Tate181fafa2009-05-14 11:12:14 -0700694 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700695 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700696 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700697 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
698 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700699 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700700 + " uid=" + p.applicationInfo.uid
701 + " killAfterRestore="
702 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
703 + " restoreNeedsApplication="
704 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
705 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700706 }
707 }
708
Dan Egnorefe52642009-06-24 00:16:33 -0700709 for (PackageInfo pkg : targetPkgs) {
710 if (packageName == null || pkg.packageName.equals(packageName)) {
711 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700712 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700713 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700714 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700715 mBackupParticipants.put(uid, set);
716 }
Dan Egnorefe52642009-06-24 00:16:33 -0700717 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700718
719 // If we've never seen this app before, schedule a backup for it
720 if (!mEverStoredApps.contains(pkg.packageName)) {
721 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
722 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700723 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700724 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700725 }
Christopher Tate487529a2009-04-29 14:03:25 -0700726 }
727 }
728
Christopher Tate6785dd82009-06-18 15:58:25 -0700729 // Remove the given package's entry from our known active set. If
730 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700731 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700732 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700733 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700734 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700735 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700736 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700737 int flags = PackageManager.GET_SIGNATURES;
738 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700739 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700740 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700741 }
742 } else {
743 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700744 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700745 }
746 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700747 }
748
Joe Onorato8ad02812009-05-13 01:41:44 -0400749 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700750 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700751 if (DEBUG) {
752 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
753 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700754 for (PackageInfo p : agents) {
755 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700756 }
757 }
Dan Egnorefe52642009-06-24 00:16:33 -0700758 for (PackageInfo pkg : agents) {
759 if (packageName == null || pkg.packageName.equals(packageName)) {
760 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700761 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700762 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700763 // Find the existing entry with the same package name, and remove it.
764 // We can't just remove(app) because the instances are different.
765 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700766 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700767 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700768 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700769 break;
770 }
771 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700772 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700773 mBackupParticipants.delete(uid);
774 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700775 }
776 }
777 }
778 }
779
Christopher Tate181fafa2009-05-14 11:12:14 -0700780 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700781 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700782 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700783 int flags = PackageManager.GET_SIGNATURES;
784 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
785 int N = packages.size();
786 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700787 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700788 try {
789 ApplicationInfo app = pkg.applicationInfo;
790 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
791 || app.backupAgentName == null
792 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
793 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
794 packages.remove(a);
795 }
796 else {
797 // we will need the shared library path, so look that up and store it here
798 app = mPackageManager.getApplicationInfo(pkg.packageName,
799 PackageManager.GET_SHARED_LIBRARY_FILES);
800 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
801 }
802 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700803 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700804 }
805 }
Dan Egnorefe52642009-06-24 00:16:33 -0700806 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700807 }
Christopher Tateaa088442009-06-16 18:25:46 -0700808
Christopher Tate3799bc22009-05-06 16:13:56 -0700809 // Reset the given package's known backup participants. Unlike add/remove, the update
810 // action cannot be passed a null package name.
811 void updatePackageParticipantsLocked(String packageName) {
812 if (packageName == null) {
813 Log.e(TAG, "updatePackageParticipants called with null package name");
814 return;
815 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700816 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700817
818 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700819 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700820 removePackageParticipantsLockedInner(packageName, allApps);
821 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700822 }
823
Christopher Tate73e02522009-07-15 14:18:26 -0700824 // Called from the backup thread: record that the given app has been successfully
825 // backed up at least once
826 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700827 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
828
829 synchronized (mEverStoredApps) {
830 if (!mEverStoredApps.add(packageName)) return;
831
832 RandomAccessFile out = null;
833 try {
834 out = new RandomAccessFile(mEverStored, "rws");
835 out.seek(out.length());
836 out.writeUTF(packageName);
837 } catch (IOException e) {
838 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
839 } finally {
840 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700841 }
842 }
843 }
844
Christopher Tatee97e8072009-07-15 16:45:50 -0700845 // Remove our awareness of having ever backed up the given package
846 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700847 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700848
Dan Egnor852f8e42009-09-30 11:20:45 -0700849 synchronized (mEverStoredApps) {
850 // Rewrite the file and rename to overwrite. If we reboot in the middle,
851 // we'll recognize on initialization time that the package no longer
852 // exists and fix it up then.
853 File tempKnownFile = new File(mBaseStateDir, "processed.new");
854 RandomAccessFile known = null;
855 try {
856 known = new RandomAccessFile(tempKnownFile, "rws");
857 mEverStoredApps.remove(packageName);
858 for (String s : mEverStoredApps) {
859 known.writeUTF(s);
860 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700861 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700862 known.close();
863 known = null;
864 if (!tempKnownFile.renameTo(mEverStored)) {
865 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
866 }
867 } catch (IOException e) {
868 // Bad: we couldn't create the new copy. For safety's sake we
869 // abandon the whole process and remove all what's-backed-up
870 // state entirely, meaning we'll force a backup pass for every
871 // participant on the next boot or [re]install.
872 Log.w(TAG, "Error rewriting " + mEverStored, e);
873 mEverStoredApps.clear();
874 tempKnownFile.delete();
875 mEverStored.delete();
876 } finally {
877 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700878 }
879 }
880 }
881
Dan Egnor87a02bc2009-06-17 02:30:10 -0700882 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700883 private IBackupTransport getTransport(String transportName) {
884 synchronized (mTransports) {
885 IBackupTransport transport = mTransports.get(transportName);
886 if (transport == null) {
887 Log.w(TAG, "Requested unavailable transport: " + transportName);
888 }
889 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700890 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700891 }
892
Christopher Tatedf01dea2009-06-09 20:45:02 -0700893 // fire off a backup agent, blocking until it attaches or times out
894 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
895 IBackupAgent agent = null;
896 synchronized(mAgentConnectLock) {
897 mConnecting = true;
898 mConnectedAgent = null;
899 try {
900 if (mActivityManager.bindBackupAgent(app, mode)) {
901 Log.d(TAG, "awaiting agent for " + app);
902
903 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700904 // only wait 10 seconds for the clear data to happen
905 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
906 while (mConnecting && mConnectedAgent == null
907 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700908 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700909 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700910 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700911 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700912 return null;
913 }
914 }
915
916 // if we timed out with no connect, abort and move on
917 if (mConnecting == true) {
918 Log.w(TAG, "Timeout waiting for agent " + app);
919 return null;
920 }
921 agent = mConnectedAgent;
922 }
923 } catch (RemoteException e) {
924 // can't happen
925 }
926 }
927 return agent;
928 }
929
Christopher Tatec7b31e32009-06-10 15:49:30 -0700930 // clear an application's data, blocking until the operation completes or times out
931 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700932 // Don't wipe packages marked allowClearUserData=false
933 try {
934 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
935 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
936 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
937 + packageName);
938 return;
939 }
940 } catch (NameNotFoundException e) {
941 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
942 return;
943 }
944
Christopher Tatec7b31e32009-06-10 15:49:30 -0700945 ClearDataObserver observer = new ClearDataObserver();
946
947 synchronized(mClearDataLock) {
948 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700949 /* This is causing some critical processes to be killed during setup.
950 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700951 try {
952 mActivityManager.clearApplicationUserData(packageName, observer);
953 } catch (RemoteException e) {
954 // can't happen because the activity manager is in this process
955 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700956 */
957 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700958
959 // only wait 10 seconds for the clear data to happen
960 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
961 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
962 try {
963 mClearDataLock.wait(5000);
964 } catch (InterruptedException e) {
965 // won't happen, but still.
966 mClearingData = false;
967 }
968 }
969 }
970 }
971
972 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -0700973 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700974 synchronized(mClearDataLock) {
975 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -0700976 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -0700977 }
978 }
979 }
980
Christopher Tate043dadc2009-06-02 16:11:00 -0700981 // ----- Back up a set of applications via a worker thread -----
982
983 class PerformBackupThread extends Thread {
984 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -0700985 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700986 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700987 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -0700988 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -0700989
Christopher Tateaa088442009-06-16 18:25:46 -0700990 public PerformBackupThread(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -0700991 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -0700992 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -0700993 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -0700994 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -0700995
996 try {
997 mStateDir = new File(mBaseStateDir, transport.transportDirName());
998 } catch (RemoteException e) {
999 // can't happen; the transport is local
1000 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001001 }
1002
1003 @Override
1004 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001005 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001006 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001007 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1008
Christopher Tate79588342009-06-30 16:11:49 -07001009 // Backups run at background priority
1010 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1011
Christopher Tate043dadc2009-06-02 16:11:00 -07001012 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001013 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001014
Dan Egnor852f8e42009-09-30 11:20:45 -07001015 // If we haven't stored package manager metadata yet, we must init the transport.
1016 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1017 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1018 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1019 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001020 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001021 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001022 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001023 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001024 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Dan Egnor726247c2009-09-29 19:12:31 -07001025 Log.e(TAG, "Transport error in initializeDevice()");
1026 }
Dan Egnor01445162009-09-21 17:04:05 -07001027 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001028
1029 // The package manager doesn't have a proper <application> etc, but since
1030 // it's running here in the system process we can just set up its agent
1031 // directly and use a synthetic BackupRequest. We always run this pass
1032 // because it's cheap and this way we guarantee that we don't get out of
1033 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001034 if (status == BackupConstants.TRANSPORT_OK) {
1035 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1036 mPackageManager, allAgentPackages());
1037 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1038 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1039 status = processOneBackup(pmRequest,
1040 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1041 }
Christopher Tate90967f42009-09-20 15:28:33 -07001042
Dan Egnor01445162009-09-21 17:04:05 -07001043 if (status == BackupConstants.TRANSPORT_OK) {
1044 // Now run all the backups in our queue
1045 status = doQueuedBackups(mTransport);
1046 }
1047
1048 if (status == BackupConstants.TRANSPORT_OK) {
1049 // Tell the transport to finish everything it has buffered
1050 status = mTransport.finishBackup();
1051 if (status == BackupConstants.TRANSPORT_OK) {
1052 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001053 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001054 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001055 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001056 Log.e(TAG, "Transport error in finishBackup()");
1057 }
1058 }
1059
Dan Egnor01445162009-09-21 17:04:05 -07001060 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001061 // The backend reports that our dataset has been wiped. We need to
1062 // reset all of our bookkeeping and instead run a new backup pass for
Dan Egnor852f8e42009-09-30 11:20:45 -07001063 // everything. This must come after mBackupOrRestoreInProgress is cleared.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001064 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001065 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001066 }
1067 } catch (Exception e) {
1068 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001069 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001070 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001071 // If things went wrong, we need to re-stage the apps we had expected
1072 // to be backing up in this pass. This journals the package names in
1073 // the current active pending-backup file, not in the we are holding
1074 // here in mJournal.
1075 if (status != BackupConstants.TRANSPORT_OK) {
1076 Log.w(TAG, "Backup pass unsuccessful, restaging");
1077 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001078 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001079 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001080
1081 // We also want to reset the backup schedule based on whatever
1082 // the transport suggests by way of retry/backoff time.
1083 try {
1084 startBackupAlarmsLocked(mTransport.requestBackupTime());
1085 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001086 }
1087
1088 // Either backup was successful, in which case we of course do not need
1089 // this pass's journal any more; or it failed, in which case we just
1090 // re-enqueued all of these packages in the current active journal.
1091 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001092 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001093 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1094 }
1095
Christopher Tate21ab6a52009-09-24 18:01:46 -07001096 // Only once we're entirely finished do we indicate our completion
1097 // and release the wakelock
1098 synchronized (mQueueLock) {
1099 mBackupOrRestoreInProgress = false;
1100 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001101
1102 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1103 // This must come after mBackupOrRestoreInProgress is cleared.
1104 backupNow();
1105 }
1106
Dan Egnorbb9001c2009-07-27 12:20:13 -07001107 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001108 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001109 }
1110
Dan Egnor01445162009-09-21 17:04:05 -07001111 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001112 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001113 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001114
Christopher Tate0749dcd2009-08-13 15:13:03 -07001115 // Don't run backup, even if requested, if the target app does not have
1116 // the requisite permission
1117 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1118 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1119 Log.w(TAG, "Skipping backup of unprivileged package "
1120 + request.appInfo.packageName);
1121 continue;
1122 }
1123
Christopher Tate043dadc2009-06-02 16:11:00 -07001124 IBackupAgent agent = null;
1125 int mode = (request.fullBackup)
1126 ? IApplicationThread.BACKUP_MODE_FULL
1127 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1128 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001129 agent = bindToAgentSynchronous(request.appInfo, mode);
1130 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001131 int result = processOneBackup(request, agent, transport);
1132 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001133 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001134 } catch (SecurityException ex) {
1135 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001136 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001137 } finally {
1138 try { // unbind even on timeout, just in case
1139 mActivityManager.unbindBackupAgent(request.appInfo);
1140 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001141 }
1142 }
Dan Egnor01445162009-09-21 17:04:05 -07001143
1144 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001145 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001146
Dan Egnor01445162009-09-21 17:04:05 -07001147 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1148 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001149 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001150 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001151
Dan Egnorbb9001c2009-07-27 12:20:13 -07001152 File savedStateName = new File(mStateDir, packageName);
1153 File backupDataName = new File(mDataDir, packageName + ".data");
1154 File newStateName = new File(mStateDir, packageName + ".new");
1155
1156 ParcelFileDescriptor savedState = null;
1157 ParcelFileDescriptor backupData = null;
1158 ParcelFileDescriptor newState = null;
1159
1160 PackageInfo packInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001161 try {
1162 // Look up the package info & signatures. This is first so that if it
1163 // throws an exception, there's no file setup yet that would need to
1164 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001165 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1166 // The metadata 'package' is synthetic
1167 packInfo = new PackageInfo();
1168 packInfo.packageName = packageName;
1169 } else {
1170 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001171 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001172 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001173
Christopher Tatec7b31e32009-06-10 15:49:30 -07001174 // In a full backup, we pass a null ParcelFileDescriptor as
1175 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001176 if (!request.fullBackup) {
1177 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001178 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001179 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1180 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001181
Dan Egnorbb9001c2009-07-27 12:20:13 -07001182 backupData = ParcelFileDescriptor.open(backupDataName,
1183 ParcelFileDescriptor.MODE_READ_WRITE |
1184 ParcelFileDescriptor.MODE_CREATE |
1185 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001186
Dan Egnorbb9001c2009-07-27 12:20:13 -07001187 newState = ParcelFileDescriptor.open(newStateName,
1188 ParcelFileDescriptor.MODE_READ_WRITE |
1189 ParcelFileDescriptor.MODE_CREATE |
1190 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001191
1192 // Run the target's backup pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001193 agent.doBackup(savedState, backupData, newState);
1194 logBackupComplete(packageName);
1195 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001196 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001197 Log.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001198 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001199 backupDataName.delete();
1200 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001201 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001202 } finally {
1203 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1204 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1205 try { if (newState != null) newState.close(); } catch (IOException e) {}
1206 savedState = backupData = newState = null;
1207 }
1208
1209 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001210 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001211 try {
1212 int size = (int) backupDataName.length();
1213 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001214 if (result == BackupConstants.TRANSPORT_OK) {
1215 backupData = ParcelFileDescriptor.open(backupDataName,
1216 ParcelFileDescriptor.MODE_READ_ONLY);
1217 result = transport.performBackup(packInfo, backupData);
1218 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001219
Dan Egnor83861e72009-09-17 16:17:55 -07001220 // TODO - We call finishBackup() for each application backed up, because
1221 // we need to know now whether it succeeded or failed. Instead, we should
1222 // hold off on finishBackup() until the end, which implies holding off on
1223 // renaming *all* the output state files (see below) until that happens.
1224
Dan Egnor01445162009-09-21 17:04:05 -07001225 if (result == BackupConstants.TRANSPORT_OK) {
1226 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001227 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001228 } else {
1229 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1230 }
1231
1232 // After successful transport, delete the now-stale data
1233 // and juggle the files so that next time we supply the agent
1234 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001235 if (result == BackupConstants.TRANSPORT_OK) {
1236 backupDataName.delete();
1237 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001238 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001239 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001240 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001241 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001242 } catch (Exception e) {
1243 Log.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001244 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001245 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001246 } finally {
1247 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001248 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001249
Dan Egnor01445162009-09-21 17:04:05 -07001250 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001251 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001252 }
1253
Christopher Tatedf01dea2009-06-09 20:45:02 -07001254
1255 // ----- Restore handling -----
1256
Christopher Tate78dd4a72009-11-04 11:49:08 -08001257 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1258 // If the target resides on the system partition, we allow it to restore
1259 // data from the like-named package in a restore set even if the signatures
1260 // do not match. (Unlike general applications, those flashed to the system
1261 // partition will be signed with the device's platform certificate, so on
1262 // different phones the same system app will have different signatures.)
1263 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1264 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1265 return true;
1266 }
1267
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001268 // Allow unsigned apps, but not signed on one device and unsigned on the other
1269 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001270 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001271 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1272 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001273 if ((storedSigs == null || storedSigs.length == 0)
1274 && (deviceSigs == null || deviceSigs.length == 0)) {
1275 return true;
1276 }
1277 if (storedSigs == null || deviceSigs == null) {
1278 return false;
1279 }
1280
Christopher Tateabce4e82009-06-18 18:35:32 -07001281 // !!! TODO: this demands that every stored signature match one
1282 // that is present on device, and does not demand the converse.
1283 // Is this this right policy?
1284 int nStored = storedSigs.length;
1285 int nDevice = deviceSigs.length;
1286
1287 for (int i=0; i < nStored; i++) {
1288 boolean match = false;
1289 for (int j=0; j < nDevice; j++) {
1290 if (storedSigs[i].equals(deviceSigs[j])) {
1291 match = true;
1292 break;
1293 }
1294 }
1295 if (!match) {
1296 return false;
1297 }
1298 }
1299 return true;
1300 }
1301
Christopher Tatedf01dea2009-06-09 20:45:02 -07001302 class PerformRestoreThread extends Thread {
1303 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001304 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001305 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001306 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001307
Christopher Tate5cbbf562009-06-22 16:44:51 -07001308 class RestoreRequest {
1309 public PackageInfo app;
1310 public int storedAppVersion;
1311
1312 RestoreRequest(PackageInfo _app, int _version) {
1313 app = _app;
1314 storedAppVersion = _version;
1315 }
1316 }
1317
Christopher Tate7d562ec2009-06-25 18:03:43 -07001318 PerformRestoreThread(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001319 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001320 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001321 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001322 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001323 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001324
1325 try {
1326 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1327 } catch (RemoteException e) {
1328 // can't happen; the transport is local
1329 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001330 }
1331
1332 @Override
1333 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001334 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001335 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001336 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001337 /**
1338 * Restore sequence:
1339 *
Dan Egnorefe52642009-06-24 00:16:33 -07001340 * 1. get the restore set description for our identity
1341 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001342 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001343 * 3. for each app in the restore queue:
1344 * 3.a. clear the app data
1345 * 3.b. get the restore data for the app from the transport
1346 * 3.c. launch the backup agent for the app
1347 * 3.d. agent.doRestore() with the data from the server
1348 * 3.e. unbind the agent [and kill the app?]
1349 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001350 *
1351 * On errors, we try our best to recover and move on to the next
1352 * application, but if necessary we abort the whole operation --
1353 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001354 */
1355
Christopher Tate7d562ec2009-06-25 18:03:43 -07001356 int error = -1; // assume error
1357
Dan Egnorefe52642009-06-24 00:16:33 -07001358 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001359 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001360 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001361 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001362
Dan Egnorefe52642009-06-24 00:16:33 -07001363 // Get the list of all packages which have backup enabled.
1364 // (Include the Package Manager metadata pseudo-package first.)
1365 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1366 PackageInfo omPackage = new PackageInfo();
1367 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1368 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001369
Dan Egnorefe52642009-06-24 00:16:33 -07001370 List<PackageInfo> agentPackages = allAgentPackages();
1371 restorePackages.addAll(agentPackages);
1372
Christopher Tate7d562ec2009-06-25 18:03:43 -07001373 // let the observer know that we're running
1374 if (mObserver != null) {
1375 try {
1376 // !!! TODO: get an actual count from the transport after
1377 // its startRestore() runs?
1378 mObserver.restoreStarting(restorePackages.size());
1379 } catch (RemoteException e) {
1380 Log.d(TAG, "Restore observer died at restoreStarting");
1381 mObserver = null;
1382 }
1383 }
1384
Dan Egnor01445162009-09-21 17:04:05 -07001385 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1386 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001387 Log.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001388 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001389 return;
1390 }
1391
1392 String packageName = mTransport.nextRestorePackage();
1393 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001394 Log.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001395 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001396 return;
1397 } else if (packageName.equals("")) {
1398 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001399 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001400 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001401 return;
1402 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1403 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1404 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001405 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001406 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001407 return;
1408 }
1409
1410 // Pull the Package Manager metadata from the restore set first
1411 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1412 mPackageManager, agentPackages);
1413 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1414
Christopher Tate8c032472009-07-02 14:28:47 -07001415 // Verify that the backup set includes metadata. If not, we can't do
1416 // signature/version verification etc, so we simply do not proceed with
1417 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001418 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001419 Log.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001420 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001421 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001422 return;
1423 }
1424
Christopher Tate7d562ec2009-06-25 18:03:43 -07001425 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001426 for (;;) {
1427 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001428
Dan Egnorefe52642009-06-24 00:16:33 -07001429 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001430 Log.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001431 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001432 return;
1433 } else if (packageName.equals("")) {
1434 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001435 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001436
Christopher Tate7d562ec2009-06-25 18:03:43 -07001437 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001438 try {
1439 mObserver.onUpdate(count);
1440 } catch (RemoteException e) {
1441 Log.d(TAG, "Restore observer died in onUpdate");
1442 mObserver = null;
1443 }
1444 }
1445
Dan Egnorefe52642009-06-24 00:16:33 -07001446 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1447 if (metaInfo == null) {
1448 Log.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001449 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001450 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001451 continue;
1452 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001453
Dan Egnorbb9001c2009-07-27 12:20:13 -07001454 PackageInfo packageInfo;
1455 try {
1456 int flags = PackageManager.GET_SIGNATURES;
1457 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1458 } catch (NameNotFoundException e) {
1459 Log.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001460 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001461 "Package missing on device");
1462 continue;
1463 }
1464
Dan Egnorefe52642009-06-24 00:16:33 -07001465 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001466 String message = "Version " + metaInfo.versionCode
1467 + " > installed version " + packageInfo.versionCode;
1468 Log.w(TAG, "Package " + packageName + ": " + message);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001469 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001470 continue;
1471 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001472
Christopher Tate78dd4a72009-11-04 11:49:08 -08001473 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001474 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001475 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001476 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001477 continue;
1478 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001479
Dan Egnorefe52642009-06-24 00:16:33 -07001480 if (DEBUG) Log.v(TAG, "Package " + packageName
1481 + " restore version [" + metaInfo.versionCode
1482 + "] is compatible with installed version ["
1483 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001484
Christopher Tate5e1ab332009-09-01 20:32:49 -07001485 // Now perform the actual restore: first clear the app's data
1486 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001487 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001488
1489 // Then set up and bind the agent (with a restricted Application object
1490 // unless the application says otherwise)
1491 boolean useRealApp = (packageInfo.applicationInfo.flags
1492 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1493 if (DEBUG && useRealApp) {
1494 Log.v(TAG, "agent requires real Application subclass for restore");
1495 }
Dan Egnorefe52642009-06-24 00:16:33 -07001496 IBackupAgent agent = bindToAgentSynchronous(
1497 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001498 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1499 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001500 if (agent == null) {
1501 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001502 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001503 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001504 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001505 }
1506
Christopher Tate5e1ab332009-09-01 20:32:49 -07001507 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001508 try {
1509 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001510 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001511 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001512 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001513 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001514
1515 // The agent was probably running with a stub Application object,
1516 // which isn't a valid run mode for the main app logic. Shut
1517 // down the app so that next time it's launched, it gets the
1518 // usual full initialization.
1519 if ((packageInfo.applicationInfo.flags
1520 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1521 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1522 + packageInfo.applicationInfo.processName);
1523 mActivityManager.killApplicationProcess(
1524 packageInfo.applicationInfo.processName,
1525 packageInfo.applicationInfo.uid);
1526 }
Dan Egnorefe52642009-06-24 00:16:33 -07001527 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001528 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001529
1530 // if we get this far, report success to the observer
1531 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001532 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001533 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001534 } catch (Exception e) {
1535 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001536 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001537 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1538
Dan Egnorefe52642009-06-24 00:16:33 -07001539 try {
1540 mTransport.finishRestore();
1541 } catch (RemoteException e) {
1542 Log.e(TAG, "Error finishing restore", e);
1543 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001544
1545 if (mObserver != null) {
1546 try {
1547 mObserver.restoreFinished(error);
1548 } catch (RemoteException e) {
1549 Log.d(TAG, "Restore observer died at restoreFinished");
1550 }
1551 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001552
1553 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001554 synchronized (mQueueLock) {
1555 mBackupOrRestoreInProgress = false;
1556 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001557 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001558 }
1559 }
1560
Dan Egnorefe52642009-06-24 00:16:33 -07001561 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1562 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001563 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001564 final String packageName = app.packageName;
1565
Dan Egnorbb9001c2009-07-27 12:20:13 -07001566 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001567
Christopher Tate0749dcd2009-08-13 15:13:03 -07001568 // Don't restore to unprivileged packages
1569 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1570 packageName) != PackageManager.PERMISSION_GRANTED) {
1571 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1572 }
1573
Christopher Tatec7b31e32009-06-10 15:49:30 -07001574 // !!! TODO: get the dirs from the transport
1575 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001576 File newStateName = new File(mStateDir, packageName + ".new");
1577 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001578
Dan Egnorbb9001c2009-07-27 12:20:13 -07001579 ParcelFileDescriptor backupData = null;
1580 ParcelFileDescriptor newState = null;
1581
1582 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001583 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001584 backupData = ParcelFileDescriptor.open(backupDataName,
1585 ParcelFileDescriptor.MODE_READ_WRITE |
1586 ParcelFileDescriptor.MODE_CREATE |
1587 ParcelFileDescriptor.MODE_TRUNCATE);
1588
Dan Egnor01445162009-09-21 17:04:05 -07001589 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001590 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001591 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001592 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001593 }
1594
1595 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001596 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001597 backupData = ParcelFileDescriptor.open(backupDataName,
1598 ParcelFileDescriptor.MODE_READ_ONLY);
1599
Dan Egnorbb9001c2009-07-27 12:20:13 -07001600 newState = ParcelFileDescriptor.open(newStateName,
1601 ParcelFileDescriptor.MODE_READ_WRITE |
1602 ParcelFileDescriptor.MODE_CREATE |
1603 ParcelFileDescriptor.MODE_TRUNCATE);
1604
1605 agent.doRestore(backupData, appVersionCode, newState);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001606
1607 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001608 //
1609 // !!! TODO: the restored data should be migrated on the server
1610 // side into the current dataset. In that case the new state file
1611 // we just created would reflect the data already extant in the
1612 // backend, so there'd be nothing more to do. Until that happens,
1613 // however, we need to make sure that we record the data to the
1614 // current backend dataset. (Yes, this means shipping the data over
1615 // the wire in both directions. That's bad, but consistency comes
1616 // first, then efficiency.) Once we introduce server-side data
1617 // migration to the newly-restored device's dataset, we will change
1618 // the following from a discard of the newly-written state to the
1619 // "correct" operation of renaming into the canonical state blob.
1620 newStateName.delete(); // TODO: remove; see above comment
1621 //newStateName.renameTo(savedStateName); // TODO: replace with this
1622
Dan Egnorbb9001c2009-07-27 12:20:13 -07001623 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001624 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001625 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001626 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001627 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001628
Christopher Tate96733042009-07-20 14:49:13 -07001629 // If the agent fails restore, it might have put the app's data
1630 // into an incoherent state. For consistency we wipe its data
1631 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001632 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001633 } finally {
1634 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001635 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1636 try { if (newState != null) newState.close(); } catch (IOException e) {}
1637 backupData = newState = null;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001638 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001639 }
1640 }
1641
Christopher Tateee0e78a2009-07-02 11:17:03 -07001642 class PerformClearThread extends Thread {
1643 IBackupTransport mTransport;
1644 PackageInfo mPackage;
1645
1646 PerformClearThread(IBackupTransport transport, PackageInfo packageInfo) {
1647 mTransport = transport;
1648 mPackage = packageInfo;
1649 }
1650
1651 @Override
1652 public void run() {
1653 try {
1654 // Clear the on-device backup state to ensure a full backup next time
1655 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1656 File stateFile = new File(stateDir, mPackage.packageName);
1657 stateFile.delete();
1658
1659 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001660 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001661 mTransport.clearBackupData(mPackage);
1662 } catch (RemoteException e) {
1663 // can't happen; the transport is local
1664 } finally {
1665 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001666 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001667 mTransport.finishBackup();
1668 } catch (RemoteException e) {
1669 // can't happen; the transport is local
1670 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001671
1672 // Last but not least, release the cpu
Christopher Tatea253f162009-09-27 15:16:44 -07001673 synchronized (mQueueLock) {
1674 mBackupOrRestoreInProgress = false;
1675 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001676 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001677 }
1678 }
1679 }
1680
Christopher Tate4cc86e12009-09-21 19:36:51 -07001681 class PerformInitializeThread extends Thread {
1682 HashSet<String> mQueue;
1683
1684 PerformInitializeThread(HashSet<String> transportNames) {
1685 mQueue = transportNames;
1686 }
1687
1688 @Override
1689 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001690 try {
1691 for (String transportName : mQueue) {
1692 IBackupTransport transport = getTransport(transportName);
1693 if (transport == null) {
1694 Log.e(TAG, "Requested init for " + transportName + " but not found");
1695 continue;
1696 }
1697
Dan Egnor726247c2009-09-29 19:12:31 -07001698 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001699 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001700 long startRealtime = SystemClock.elapsedRealtime();
1701 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001702
Christopher Tate4cc86e12009-09-21 19:36:51 -07001703 if (status == BackupConstants.TRANSPORT_OK) {
1704 status = transport.finishBackup();
1705 }
1706
1707 // Okay, the wipe really happened. Clean up our local bookkeeping.
1708 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001709 Log.i(TAG, "Device init successful");
1710 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001711 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001712 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001713 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001714 synchronized (mQueueLock) {
1715 recordInitPendingLocked(false, transportName);
1716 }
Dan Egnor726247c2009-09-29 19:12:31 -07001717 } else {
1718 // If this didn't work, requeue this one and try again
1719 // after a suitable interval
1720 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001721 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001722 synchronized (mQueueLock) {
1723 recordInitPendingLocked(true, transportName);
1724 }
1725 // do this via another alarm to make sure of the wakelock states
1726 long delay = transport.requestBackupTime();
1727 if (DEBUG) Log.w(TAG, "init failed on "
1728 + transportName + " resched in " + delay);
1729 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1730 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001731 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001732 }
1733 } catch (RemoteException e) {
1734 // can't happen; the transports are local
1735 } catch (Exception e) {
1736 Log.e(TAG, "Unexpected error performing init", e);
1737 } finally {
1738 // Done; indicate that we're finished and release the wakelock
1739 synchronized (mQueueLock) {
1740 mInitInProgress = false;
1741 }
1742 mWakelock.release();
1743 }
1744 }
1745 }
1746
Christopher Tatedf01dea2009-06-09 20:45:02 -07001747
Christopher Tate487529a2009-04-29 14:03:25 -07001748 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001749
Dan Egnor852f8e42009-09-30 11:20:45 -07001750 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001751 // Record that we need a backup pass for the caller. Since multiple callers
1752 // may share a uid, we need to note all candidates within that uid and schedule
1753 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001754 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001755
Christopher Tate63d27002009-06-16 17:16:42 -07001756 // If the caller does not hold the BACKUP permission, it can only request a
1757 // backup of its own data.
1758 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001759 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001760 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1761 targets = mBackupParticipants.get(Binder.getCallingUid());
1762 } else {
1763 // a caller with full permission can ask to back up any participating app
1764 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001765 targets = new HashSet<ApplicationInfo>();
1766 int N = mBackupParticipants.size();
1767 for (int i = 0; i < N; i++) {
1768 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1769 if (s != null) {
1770 targets.addAll(s);
1771 }
1772 }
1773 }
Christopher Tate487529a2009-04-29 14:03:25 -07001774 if (targets != null) {
1775 synchronized (mQueueLock) {
1776 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001777 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001778 // validate the caller-supplied package name against the known set of
1779 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001780 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001781 // Add the caller to the set of pending backups. If there is
1782 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001783 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001784 if (mPendingBackups.put(app, req) == null) {
1785 // Journal this request in case of crash. The put()
1786 // operation returned null when this package was not already
1787 // in the set; we want to avoid touching the disk redundantly.
1788 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001789
Christopher Tate22b60d82009-07-07 16:36:02 -07001790 if (DEBUG) {
1791 int numKeys = mPendingBackups.size();
1792 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1793 for (BackupRequest b : mPendingBackups.values()) {
1794 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1795 }
1796 }
1797 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001798 }
1799 }
Christopher Tate487529a2009-04-29 14:03:25 -07001800 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001801 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001802 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1803 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001804 }
1805 }
Christopher Tate46758122009-05-06 11:22:00 -07001806
Christopher Tatecde87f42009-06-12 12:55:53 -07001807 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001808 RandomAccessFile out = null;
1809 try {
1810 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1811 out = new RandomAccessFile(mJournal, "rws");
1812 out.seek(out.length());
1813 out.writeUTF(str);
1814 } catch (IOException e) {
1815 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1816 mJournal = null;
1817 } finally {
1818 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001819 }
1820 }
1821
Christopher Tateee0e78a2009-07-02 11:17:03 -07001822 // Clear the given package's backup data from the current transport
1823 public void clearBackupData(String packageName) {
1824 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1825 PackageInfo info;
1826 try {
1827 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1828 } catch (NameNotFoundException e) {
1829 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1830 return;
1831 }
1832
1833 // If the caller does not hold the BACKUP permission, it can only request a
1834 // wipe of its own backed-up data.
1835 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001836 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001837 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1838 apps = mBackupParticipants.get(Binder.getCallingUid());
1839 } else {
1840 // a caller with full permission can ask to back up any participating app
1841 // !!! TODO: allow data-clear of ANY app?
1842 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1843 apps = new HashSet<ApplicationInfo>();
1844 int N = mBackupParticipants.size();
1845 for (int i = 0; i < N; i++) {
1846 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1847 if (s != null) {
1848 apps.addAll(s);
1849 }
1850 }
1851 }
1852
1853 // now find the given package in the set of candidate apps
1854 for (ApplicationInfo app : apps) {
1855 if (app.packageName.equals(packageName)) {
1856 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1857 // found it; fire off the clear request
1858 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001859 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001860 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001861 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1862 new ClearParams(getTransport(mCurrentTransport), info));
1863 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001864 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001865 }
1866 break;
1867 }
1868 }
1869 }
1870
Christopher Tateace7f092009-06-15 18:07:25 -07001871 // Run a backup pass immediately for any applications that have declared
1872 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07001873 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04001874 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001875
Christopher Tateace7f092009-06-15 18:07:25 -07001876 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001877 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001878 // Because the alarms we are using can jitter, and we want an *immediate*
1879 // backup pass to happen, we restart the timer beginning with "next time,"
1880 // then manually fire the backup trigger intent ourselves.
1881 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001882 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001883 mRunBackupIntent.send();
1884 } catch (PendingIntent.CanceledException e) {
1885 // should never happen
1886 Log.e(TAG, "run-backup intent cancelled!");
1887 }
Christopher Tate46758122009-05-06 11:22:00 -07001888 }
1889 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001890
Christopher Tate8031a3d2009-07-06 16:36:05 -07001891 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001892 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001893 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1894 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001895
Christopher Tate4cc86e12009-09-21 19:36:51 -07001896 Log.i(TAG, "Backup enabled => " + enable);
1897
Christopher Tate6ef58a12009-06-29 14:56:28 -07001898 boolean wasEnabled = mEnabled;
1899 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001900 Settings.Secure.putInt(mContext.getContentResolver(),
1901 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001902 mEnabled = enable;
1903 }
1904
Christopher Tate49401dd2009-07-01 12:34:29 -07001905 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001906 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001907 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001908 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001909 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001910 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001911 if (DEBUG) Log.i(TAG, "Opting out of backup");
1912
Christopher Tateb6787f22009-07-02 17:40:45 -07001913 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001914
1915 // This also constitutes an opt-out, so we wipe any data for
1916 // this device from the backend. We start that process with
1917 // an alarm in order to guarantee wakelock states.
1918 if (wasEnabled && mProvisioned) {
1919 // NOTE: we currently flush every registered transport, not just
1920 // the currently-active one.
1921 HashSet<String> allTransports;
1922 synchronized (mTransports) {
1923 allTransports = new HashSet<String>(mTransports.keySet());
1924 }
1925 // build the set of transports for which we are posting an init
1926 for (String transport : allTransports) {
1927 recordInitPendingLocked(true, transport);
1928 }
1929 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1930 mRunInitIntent);
1931 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001932 }
1933 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001934 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001935
Christopher Tate8031a3d2009-07-06 16:36:05 -07001936 // Mark the backup service as having been provisioned
1937 public void setBackupProvisioned(boolean available) {
1938 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1939 "setBackupProvisioned");
1940
1941 boolean wasProvisioned = mProvisioned;
1942 synchronized (this) {
1943 Settings.Secure.putInt(mContext.getContentResolver(),
1944 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
1945 mProvisioned = available;
1946 }
1947
1948 synchronized (mQueueLock) {
1949 if (available && !wasProvisioned && mEnabled) {
1950 // we're now good to go, so start the backup alarms
1951 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
1952 } else if (!available) {
1953 // No longer enabled, so stop running backups
1954 Log.w(TAG, "Backup service no longer provisioned");
1955 mAlarmManager.cancel(mRunBackupIntent);
1956 }
1957 }
1958 }
1959
1960 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07001961 // We used to use setInexactRepeating(), but that may be linked to
1962 // backups running at :00 more often than not, creating load spikes.
1963 // Schedule at an exact time for now, and also add a bit of "fuzz".
1964
1965 Random random = new Random();
1966 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
1967 random.nextInt(FUZZ_MILLIS);
1968 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
1969 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07001970 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07001971 }
1972
Christopher Tate6ef58a12009-06-29 14:56:28 -07001973 // Report whether the backup mechanism is currently enabled
1974 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04001975 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001976 return mEnabled; // no need to synchronize just to read it
1977 }
1978
Christopher Tate91717492009-06-26 21:07:13 -07001979 // Report the name of the currently active transport
1980 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04001981 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001982 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001983 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07001984 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07001985 }
1986
Christopher Tate91717492009-06-26 21:07:13 -07001987 // Report all known, available backup transports
1988 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07001989 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07001990
Christopher Tate91717492009-06-26 21:07:13 -07001991 String[] list = null;
1992 ArrayList<String> known = new ArrayList<String>();
1993 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
1994 if (entry.getValue() != null) {
1995 known.add(entry.getKey());
1996 }
1997 }
1998
1999 if (known.size() > 0) {
2000 list = new String[known.size()];
2001 known.toArray(list);
2002 }
2003 return list;
2004 }
2005
2006 // Select which transport to use for the next backup operation. If the given
2007 // name is not one of the available transports, no action is taken and the method
2008 // returns null.
2009 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002010 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002011
2012 synchronized (mTransports) {
2013 String prevTransport = null;
2014 if (mTransports.get(transport) != null) {
2015 prevTransport = mCurrentTransport;
2016 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002017 Settings.Secure.putString(mContext.getContentResolver(),
2018 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002019 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2020 + " returning " + prevTransport);
2021 } else {
2022 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2023 }
2024 return prevTransport;
2025 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002026 }
2027
2028 // Callback: a requested backup agent has been instantiated. This should only
2029 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002030 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002031 synchronized(mAgentConnectLock) {
2032 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2033 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2034 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2035 mConnectedAgent = agent;
2036 mConnecting = false;
2037 } else {
2038 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2039 + " claiming agent connected");
2040 }
2041 mAgentConnectLock.notifyAll();
2042 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002043 }
2044
2045 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2046 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002047 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002048 public void agentDisconnected(String packageName) {
2049 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002050 synchronized(mAgentConnectLock) {
2051 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2052 mConnectedAgent = null;
2053 mConnecting = false;
2054 } else {
2055 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2056 + " claiming agent disconnected");
2057 }
2058 mAgentConnectLock.notifyAll();
2059 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002060 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002061
Christopher Tate8c850b72009-06-07 19:33:20 -07002062 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002063 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002064 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002065
2066 synchronized(this) {
2067 if (mActiveRestoreSession != null) {
2068 Log.d(TAG, "Restore session requested but one already active");
2069 return null;
2070 }
Christopher Tate91717492009-06-26 21:07:13 -07002071 mActiveRestoreSession = new RestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002072 }
2073 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002074 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002075
Christopher Tate9b3905c2009-06-08 15:24:01 -07002076 // ----- Restore session -----
2077
2078 class RestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002079 private static final String TAG = "RestoreSession";
2080
Christopher Tate9b3905c2009-06-08 15:24:01 -07002081 private IBackupTransport mRestoreTransport = null;
2082 RestoreSet[] mRestoreSets = null;
2083
Christopher Tate91717492009-06-26 21:07:13 -07002084 RestoreSession(String transport) {
2085 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002086 }
2087
2088 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002089 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002090 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002091 "getAvailableRestoreSets");
2092
Christopher Tatef68eb502009-06-16 11:02:01 -07002093 try {
Christopher Tate43383042009-07-13 15:17:13 -07002094 if (mRestoreTransport == null) {
2095 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002096 return null;
2097 }
2098 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002099 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002100 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002101 }
2102 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002103 } catch (Exception e) {
2104 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2105 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002106 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002107 }
2108
Dan Egnor0084da52009-07-29 12:57:16 -07002109 public synchronized int performRestore(long token, IRestoreObserver observer) {
2110 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2111 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002112
Christopher Tatef2c321a2009-08-10 15:43:36 -07002113 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2114 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002115
Dan Egnor0084da52009-07-29 12:57:16 -07002116 if (mRestoreTransport == null || mRestoreSets == null) {
2117 Log.e(TAG, "Ignoring performRestore() with no restore set");
2118 return -1;
2119 }
2120
Christopher Tate21ab6a52009-09-24 18:01:46 -07002121 synchronized (mQueueLock) {
2122 if (mBackupOrRestoreInProgress) {
2123 Log.e(TAG, "Backup pass in progress, restore aborted");
2124 return -1;
2125 }
2126
2127 for (int i = 0; i < mRestoreSets.length; i++) {
2128 if (token == mRestoreSets[i].token) {
2129 long oldId = Binder.clearCallingIdentity();
2130 // Suppress backups until the restore operation is finished
2131 mBackupOrRestoreInProgress = true;
2132 mWakelock.acquire();
2133 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2134 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2135 mBackupHandler.sendMessage(msg);
2136 Binder.restoreCallingIdentity(oldId);
2137 return 0;
2138 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002139 }
2140 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002141
2142 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002143 return -1;
2144 }
2145
Dan Egnor0084da52009-07-29 12:57:16 -07002146 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002147 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002148 "endRestoreSession");
2149
Dan Egnor0084da52009-07-29 12:57:16 -07002150 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002151
Dan Egnor0084da52009-07-29 12:57:16 -07002152 synchronized (this) {
2153 try {
2154 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2155 } catch (Exception e) {
2156 Log.e(TAG, "Error in finishRestore", e);
2157 } finally {
2158 mRestoreTransport = null;
2159 }
2160 }
2161
2162 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002163 if (BackupManagerService.this.mActiveRestoreSession == this) {
2164 BackupManagerService.this.mActiveRestoreSession = null;
2165 } else {
2166 Log.e(TAG, "ending non-current restore session");
2167 }
2168 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002169 }
2170 }
2171
Christopher Tate043dadc2009-06-02 16:11:00 -07002172
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002173 @Override
2174 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2175 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002176 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002177 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
2178 + (!mBackupOrRestoreInProgress ? "not " : "") + "in progress / "
2179 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init / "
2180 + (!mInitInProgress ? "not " : "") + "initializing");
2181 pw.println("Last backup pass: " + mLastBackupPass
2182 + " (now = " + System.currentTimeMillis() + ')');
2183 pw.println(" next scheduled: " + mNextBackupPass);
2184
Christopher Tate91717492009-06-26 21:07:13 -07002185 pw.println("Available transports:");
2186 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002187 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2188 try {
2189 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2190 for (File f : dir.listFiles()) {
2191 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2192 }
2193 } catch (RemoteException e) {
2194 Log.e(TAG, "Error in transportDirName()", e);
2195 pw.println(" Error: " + e);
2196 }
Christopher Tate91717492009-06-26 21:07:13 -07002197 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002198
2199 pw.println("Pending init: " + mPendingInits.size());
2200 for (String s : mPendingInits) {
2201 pw.println(" " + s);
2202 }
2203
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002204 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002205 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002206 for (int i=0; i<N; i++) {
2207 int uid = mBackupParticipants.keyAt(i);
2208 pw.print(" uid: ");
2209 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002210 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2211 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002212 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002213 }
2214 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002215
Christopher Tate73e02522009-07-15 14:18:26 -07002216 pw.println("Ever backed up: " + mEverStoredApps.size());
2217 for (String pkg : mEverStoredApps) {
2218 pw.println(" " + pkg);
2219 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002220
2221 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002222 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002223 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002224 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002225 }
2226 }
Christopher Tate487529a2009-04-29 14:03:25 -07002227}