blob: 0c1e0602ea3b8fc213397e05547e4391713f18a0 [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;
Christopher Tate44a27902010-01-27 17:15:49 -080046import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070047import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080048import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070049import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070050import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070051import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070052import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070053import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070054import android.os.SystemClock;
Oscar Montemayora8529f62009-11-18 10:14:20 -080055import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070056import android.util.EventLog;
Christopher Tate487529a2009-04-29 14:03:25 -070057import android.util.Log;
58import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080059import android.util.SparseIntArray;
Christopher Tate487529a2009-04-29 14:03:25 -070060
Christopher Tated55e18a2009-09-21 10:12:59 -070061import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070062import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080063import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070064import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070065
Christopher Tatecde87f42009-06-12 12:55:53 -070066import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070067import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068import java.io.FileDescriptor;
Christopher Tate4cc86e12009-09-21 19:36:51 -070069import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070070import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070071import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070072import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040073import java.util.ArrayList;
74import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070075import java.util.HashSet;
76import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070077import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070078import java.util.Random;
Christopher Tate487529a2009-04-29 14:03:25 -070079
80class BackupManagerService extends IBackupManager.Stub {
81 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070082 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070083
Christopher Tate49401dd2009-07-01 12:34:29 -070084 // How often we perform a backup pass. Privileged external callers can
85 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070086 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070087
Dan Egnorc1c49c02009-10-30 17:35:39 -070088 // Random variation in backup scheduling time to avoid server load spikes
89 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
90
Christopher Tate8031a3d2009-07-06 16:36:05 -070091 // The amount of time between the initial provisioning of the device and
92 // the first backup pass.
93 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
94
Christopher Tate4cc86e12009-09-21 19:36:51 -070095 private static final String RUN_BACKUP_ACTION = "android.backup.intent.RUN";
96 private static final String RUN_INITIALIZE_ACTION = "android.backup.intent.INIT";
97 private static final String RUN_CLEAR_ACTION = "android.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -070098 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070099 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700100 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700101 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700102 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate44a27902010-01-27 17:15:49 -0800103 private static final int MSG_TIMEOUT = 6;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700104
105 // Timeout interval for deciding that a bind or clear-data has taken too long
106 static final long TIMEOUT_INTERVAL = 10 * 1000;
107
Christopher Tate44a27902010-01-27 17:15:49 -0800108 // Timeout intervals for agent backup & restore operations
109 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
110 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
111
Christopher Tate487529a2009-04-29 14:03:25 -0700112 private Context mContext;
113 private PackageManager mPackageManager;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700114 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700115 private PowerManager mPowerManager;
116 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800117 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700118
Christopher Tate73e02522009-07-15 14:18:26 -0700119 boolean mEnabled; // access to this is synchronized on 'this'
120 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800121 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700122 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800123 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
124 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700125 PendingIntent mRunBackupIntent, mRunInitIntent;
126 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700127 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700128 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700129 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700130 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700131 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700132 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700133 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700134
Christopher Tate181fafa2009-05-14 11:12:14 -0700135 BackupRequest(ApplicationInfo app, boolean isFull) {
136 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700137 fullBackup = isFull;
138 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700139
140 public String toString() {
141 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
142 }
Christopher Tate46758122009-05-06 11:22:00 -0700143 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400144 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700145 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700146 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700147
148 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700149 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700150
151 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700152 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700153
Christopher Tate043dadc2009-06-02 16:11:00 -0700154 // The thread performing the sequence of queued backups binds to each app's agent
155 // in succession. Bind notifications are asynchronously delivered through the
156 // Activity Manager; use this lock object to signal when a requested binding has
157 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700158 final Object mAgentConnectLock = new Object();
159 IBackupAgent mConnectedAgent;
160 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700161 volatile long mLastBackupPass;
162 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700163
Christopher Tate55f931a2009-09-29 17:17:34 -0700164 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700165 final Object mClearDataLock = new Object();
166 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700167
Christopher Tate91717492009-06-26 21:07:13 -0700168 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700169 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700170 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700171 String mCurrentTransport;
172 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800173 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700174
Christopher Tate73e02522009-07-15 14:18:26 -0700175 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700176 public IBackupTransport transport;
177 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700178 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700179
Dan Egnor156411d2009-06-26 13:20:02 -0700180 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700181 transport = _transport;
182 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700183 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700184 }
185 }
186
Christopher Tate73e02522009-07-15 14:18:26 -0700187 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700188 public IBackupTransport transport;
189 public PackageInfo packageInfo;
190
191 ClearParams(IBackupTransport _transport, PackageInfo _info) {
192 transport = _transport;
193 packageInfo = _info;
194 }
195 }
196
Christopher Tate44a27902010-01-27 17:15:49 -0800197 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
198 // token is the index of the entry in the pending-operations list.
199 static final int OP_PENDING = 0;
200 static final int OP_ACKNOWLEDGED = 1;
201 static final int OP_TIMEOUT = -1;
202
203 final SparseIntArray mCurrentOperations = new SparseIntArray();
204 final Object mCurrentOpLock = new Object();
205 final Random mTokenGenerator = new Random();
206
Christopher Tate5cb400b2009-06-25 16:03:14 -0700207 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700208 File mBaseStateDir;
209 File mDataDir;
210 File mJournalDir;
211 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700212
213 // Keep a log of all the apps we've ever backed up
214 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700215 HashSet<String> mEverStoredApps = new HashSet<String>();
216
Christopher Tate4cc86e12009-09-21 19:36:51 -0700217 // Persistently track the need to do a full init
218 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
219 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700220
Christopher Tate44a27902010-01-27 17:15:49 -0800221 // ----- Asynchronous backup/restore handler thread -----
222
223 private class BackupHandler extends Handler {
224 public BackupHandler(Looper looper) {
225 super(looper);
226 }
227
228 public void handleMessage(Message msg) {
229
230 switch (msg.what) {
231 case MSG_RUN_BACKUP:
232 {
233 mLastBackupPass = System.currentTimeMillis();
234 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
235
236 IBackupTransport transport = getTransport(mCurrentTransport);
237 if (transport == null) {
238 Log.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800239 mWakelock.release();
240 break;
241 }
242
243 // snapshot the pending-backup set and work on that
244 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
245 synchronized (mQueueLock) {
246 // Do we have any work to do?
247 if (mPendingBackups.size() > 0) {
248 for (BackupRequest b: mPendingBackups.values()) {
249 queue.add(b);
250 }
251 if (DEBUG) Log.v(TAG, "clearing pending backups");
252 mPendingBackups.clear();
253
254 // Start a new backup-queue journal file too
255 File oldJournal = mJournal;
256 mJournal = null;
257
258 // At this point, we have started a new journal file, and the old
259 // file identity is being passed to the backup processing thread.
260 // When it completes successfully, that old journal file will be
261 // deleted. If we crash prior to that, the old journal is parsed
262 // at next boot and the journaled requests fulfilled.
263 (new PerformBackupTask(transport, queue, oldJournal)).run();
264 } else {
265 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tate44a27902010-01-27 17:15:49 -0800266 mWakelock.release();
267 }
268 }
269 break;
270 }
271
272 case MSG_RUN_FULL_BACKUP:
273 break;
274
275 case MSG_RUN_RESTORE:
276 {
277 RestoreParams params = (RestoreParams)msg.obj;
278 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
279 (new PerformRestoreTask(params.transport, params.observer,
280 params.token)).run();
281 break;
282 }
283
284 case MSG_RUN_CLEAR:
285 {
286 ClearParams params = (ClearParams)msg.obj;
287 (new PerformClearTask(params.transport, params.packageInfo)).run();
288 break;
289 }
290
291 case MSG_RUN_INITIALIZE:
292 {
293 HashSet<String> queue;
294
295 // Snapshot the pending-init queue and work on that
296 synchronized (mQueueLock) {
297 queue = new HashSet<String>(mPendingInits);
298 mPendingInits.clear();
299 }
300
301 (new PerformInitializeTask(queue)).run();
302 break;
303 }
304
305 case MSG_TIMEOUT:
306 {
307 synchronized (mCurrentOpLock) {
308 final int token = msg.arg1;
309 int state = mCurrentOperations.get(token, OP_TIMEOUT);
310 if (state == OP_PENDING) {
311 if (DEBUG) Log.v(TAG, "TIMEOUT: token=" + token);
312 mCurrentOperations.put(token, OP_TIMEOUT);
313 }
314 mCurrentOpLock.notifyAll();
315 }
316 break;
317 }
318 }
319 }
320 }
321
322 // ----- Main service implementation -----
323
Christopher Tate487529a2009-04-29 14:03:25 -0700324 public BackupManagerService(Context context) {
325 mContext = context;
326 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700327 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700328
Christopher Tateb6787f22009-07-02 17:40:45 -0700329 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
330 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
331
Christopher Tate44a27902010-01-27 17:15:49 -0800332 mBackupManagerBinder = asInterface(asBinder());
333
334 // spin up the backup/restore handler thread
335 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
336 mHandlerThread.start();
337 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
338
Christopher Tate22b87872009-05-04 16:41:53 -0700339 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700340 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700341 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700342 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700343 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800344 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
345 Settings.Secure.BACKUP_AUTO_RESTORE, 0) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800346 // If Encrypted file systems is enabled or disabled, this call will return the
347 // correct directory.
348 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
349 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700350 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700351
Christopher Tate4cc86e12009-09-21 19:36:51 -0700352 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700353 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700354 IntentFilter filter = new IntentFilter();
355 filter.addAction(RUN_BACKUP_ACTION);
356 context.registerReceiver(mRunBackupReceiver, filter,
357 android.Manifest.permission.BACKUP, null);
358
359 mRunInitReceiver = new RunInitializeReceiver();
360 filter = new IntentFilter();
361 filter.addAction(RUN_INITIALIZE_ACTION);
362 context.registerReceiver(mRunInitReceiver, filter,
363 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700364
365 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700366 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
367 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
368
Christopher Tate4cc86e12009-09-21 19:36:51 -0700369 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
370 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
371 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
372
Christopher Tatecde87f42009-06-12 12:55:53 -0700373 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700374 mJournalDir = new File(mBaseStateDir, "pending");
375 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700376 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700377
Christopher Tate73e02522009-07-15 14:18:26 -0700378 // Set up the various sorts of package tracking we do
379 initPackageTracking();
380
Christopher Tateabce4e82009-06-18 18:35:32 -0700381 // Build our mapping of uid to backup client services. This implicitly
382 // schedules a backup pass on the Package Manager metadata the first
383 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700384 synchronized (mBackupParticipants) {
385 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700386 }
387
Dan Egnor87a02bc2009-06-17 02:30:10 -0700388 // Set up our transport options and initialize the default transport
389 // TODO: Have transports register themselves somehow?
390 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700391 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700392 ComponentName localName = new ComponentName(context, LocalTransport.class);
393 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700394
Christopher Tate91717492009-06-26 21:07:13 -0700395 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700396 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
397 Settings.Secure.BACKUP_TRANSPORT);
398 if ("".equals(mCurrentTransport)) {
399 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700400 }
Christopher Tate91717492009-06-26 21:07:13 -0700401 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
402
403 // Attach to the Google backup transport. When this comes up, it will set
404 // itself as the current transport because we explicitly reset mCurrentTransport
405 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700406 Intent intent = new Intent().setComponent(new ComponentName(
407 "com.google.android.backup",
408 "com.google.android.backup.BackupTransportService"));
409 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700410
Christopher Tatecde87f42009-06-12 12:55:53 -0700411 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700412 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700413 parseLeftoverJournals();
414
Christopher Tateb6787f22009-07-02 17:40:45 -0700415 // Power management
416 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
417
418 // Start the backup passes going
419 setBackupEnabled(areEnabled);
420 }
421
422 private class RunBackupReceiver extends BroadcastReceiver {
423 public void onReceive(Context context, Intent intent) {
424 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700425 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700426 if (mPendingInits.size() > 0) {
427 // If there are pending init operations, we process those
428 // and then settle into the usual periodic backup schedule.
429 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
430 try {
431 mAlarmManager.cancel(mRunInitIntent);
432 mRunInitIntent.send();
433 } catch (PendingIntent.CanceledException ce) {
434 Log.e(TAG, "Run init intent cancelled");
435 // can't really do more than bail here
436 }
437 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800438 // Don't run backups now if we're disabled or not yet
439 // fully set up.
440 if (mEnabled && mProvisioned) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700441 if (DEBUG) Log.v(TAG, "Running a backup pass");
442
443 // Acquire the wakelock and pass it to the backup thread. it will
444 // be released once backup concludes.
445 mWakelock.acquire();
446
447 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
448 mBackupHandler.sendMessage(msg);
449 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800450 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700451 }
452 }
453 }
454 }
455 }
456 }
457
458 private class RunInitializeReceiver extends BroadcastReceiver {
459 public void onReceive(Context context, Intent intent) {
460 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
461 synchronized (mQueueLock) {
462 if (DEBUG) Log.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700463
464 // Acquire the wakelock and pass it to the init thread. it will
465 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700466 mWakelock.acquire();
467
Christopher Tate4cc86e12009-09-21 19:36:51 -0700468 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700469 mBackupHandler.sendMessage(msg);
470 }
471 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700472 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700473 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700474
Christopher Tate73e02522009-07-15 14:18:26 -0700475 private void initPackageTracking() {
476 if (DEBUG) Log.v(TAG, "Initializing package tracking");
477
Christopher Tatee97e8072009-07-15 16:45:50 -0700478 // Keep a log of what apps we've ever backed up. Because we might have
479 // rebooted in the middle of an operation that was removing something from
480 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700481 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700482 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700483
Christopher Tatee97e8072009-07-15 16:45:50 -0700484 // If we were in the middle of removing something from the ever-backed-up
485 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700486 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700487 if (tempProcessedFile.exists()) {
488 tempProcessedFile.delete();
489 }
490
Dan Egnor852f8e42009-09-30 11:20:45 -0700491 // If there are previous contents, parse them out then start a new
492 // file to continue the recordkeeping.
493 if (mEverStored.exists()) {
494 RandomAccessFile temp = null;
495 RandomAccessFile in = null;
496
497 try {
498 temp = new RandomAccessFile(tempProcessedFile, "rws");
499 in = new RandomAccessFile(mEverStored, "r");
500
501 while (true) {
502 PackageInfo info;
503 String pkg = in.readUTF();
504 try {
505 info = mPackageManager.getPackageInfo(pkg, 0);
506 mEverStoredApps.add(pkg);
507 temp.writeUTF(pkg);
508 if (DEBUG) Log.v(TAG, " + " + pkg);
509 } catch (NameNotFoundException e) {
510 // nope, this package was uninstalled; don't include it
511 if (DEBUG) Log.v(TAG, " - " + pkg);
512 }
513 }
514 } catch (EOFException e) {
515 // Once we've rewritten the backup history log, atomically replace the
516 // old one with the new one then reopen the file for continuing use.
517 if (!tempProcessedFile.renameTo(mEverStored)) {
518 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
519 }
520 } catch (IOException e) {
521 Log.e(TAG, "Error in processed file", e);
522 } finally {
523 try { if (temp != null) temp.close(); } catch (IOException e) {}
524 try { if (in != null) in.close(); } catch (IOException e) {}
525 }
526 }
527
Christopher Tate73e02522009-07-15 14:18:26 -0700528 // Register for broadcasts about package install, etc., so we can
529 // update the provider list.
530 IntentFilter filter = new IntentFilter();
531 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
532 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
533 filter.addDataScheme("package");
534 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800535 // Register for events related to sdcard installation.
536 IntentFilter sdFilter = new IntentFilter();
537 sdFilter.addAction(Intent.ACTION_MEDIA_RESOURCES_AVAILABLE);
538 sdFilter.addAction(Intent.ACTION_MEDIA_RESOURCES_UNAVAILABLE);
539 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700540 }
541
Christopher Tatecde87f42009-06-12 12:55:53 -0700542 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700543 for (File f : mJournalDir.listFiles()) {
544 if (mJournal == null || f.compareTo(mJournal) != 0) {
545 // This isn't the current journal, so it must be a leftover. Read
546 // out the package names mentioned there and schedule them for
547 // backup.
548 RandomAccessFile in = null;
549 try {
550 Log.i(TAG, "Found stale backup journal, scheduling:");
551 in = new RandomAccessFile(f, "r");
552 while (true) {
553 String packageName = in.readUTF();
554 Log.i(TAG, " + " + packageName);
555 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700556 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700557 } catch (EOFException e) {
558 // no more data; we're done
559 } catch (Exception e) {
560 Log.e(TAG, "Can't read " + f, e);
561 } finally {
562 // close/delete the file
563 try { if (in != null) in.close(); } catch (IOException e) {}
564 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700565 }
566 }
567 }
568 }
569
Christopher Tate4cc86e12009-09-21 19:36:51 -0700570 // Maintain persistent state around whether need to do an initialize operation.
571 // Must be called with the queue lock held.
572 void recordInitPendingLocked(boolean isPending, String transportName) {
573 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
574 + " on transport " + transportName);
575 try {
576 IBackupTransport transport = getTransport(transportName);
577 String transportDirName = transport.transportDirName();
578 File stateDir = new File(mBaseStateDir, transportDirName);
579 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
580
581 if (isPending) {
582 // We need an init before we can proceed with sending backup data.
583 // Record that with an entry in our set of pending inits, as well as
584 // journaling it via creation of a sentinel file.
585 mPendingInits.add(transportName);
586 try {
587 (new FileOutputStream(initPendingFile)).close();
588 } catch (IOException ioe) {
589 // Something is badly wrong with our permissions; just try to move on
590 }
591 } else {
592 // No more initialization needed; wipe the journal and reset our state.
593 initPendingFile.delete();
594 mPendingInits.remove(transportName);
595 }
596 } catch (RemoteException e) {
597 // can't happen; the transport is local
598 }
599 }
600
Christopher Tated55e18a2009-09-21 10:12:59 -0700601 // Reset all of our bookkeeping, in response to having been told that
602 // the backend data has been wiped [due to idle expiry, for example],
603 // so we must re-upload all saved settings.
604 void resetBackupState(File stateFileDir) {
605 synchronized (mQueueLock) {
606 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700607 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700608 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700609
610 // Remove all the state files
611 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700612 // ... but don't touch the needs-init sentinel
613 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
614 sf.delete();
615 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700616 }
617
618 // Enqueue a new backup of every participant
619 int N = mBackupParticipants.size();
620 for (int i=0; i<N; i++) {
621 int uid = mBackupParticipants.keyAt(i);
622 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
623 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700624 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700625 }
626 }
627 }
628 }
629
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800630 // Add a transport to our set of available backends. If 'transport' is null, this
631 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700632 private void registerTransport(String name, IBackupTransport transport) {
633 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700634 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800635 if (transport != null) {
636 mTransports.put(name, transport);
637 } else {
638 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800639 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800640 mCurrentTransport = null;
641 }
642 // Nothing further to do in the unregistration case
643 return;
644 }
Christopher Tate91717492009-06-26 21:07:13 -0700645 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700646
647 // If the init sentinel file exists, we need to be sure to perform the init
648 // as soon as practical. We also create the state directory at registration
649 // time to ensure it's present from the outset.
650 try {
651 String transportName = transport.transportDirName();
652 File stateDir = new File(mBaseStateDir, transportName);
653 stateDir.mkdirs();
654
655 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
656 if (initSentinel.exists()) {
657 synchronized (mQueueLock) {
658 mPendingInits.add(transportName);
659
660 // TODO: pick a better starting time than now + 1 minute
661 long delay = 1000 * 60; // one minute, in milliseconds
662 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
663 System.currentTimeMillis() + delay, mRunInitIntent);
664 }
665 }
666 } catch (RemoteException e) {
667 // can't happen, the transport is local
668 }
Christopher Tate91717492009-06-26 21:07:13 -0700669 }
670
Christopher Tate3799bc22009-05-06 16:13:56 -0700671 // ----- Track installation/removal of packages -----
672 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
673 public void onReceive(Context context, Intent intent) {
674 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
675
Christopher Tate3799bc22009-05-06 16:13:56 -0700676 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800677 boolean replacing = false;
678 boolean added = false;
679 Bundle extras = intent.getExtras();
680 String pkgList[] = null;
681 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
682 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
683 Uri uri = intent.getData();
684 if (uri == null) {
685 return;
686 }
687 String pkgName = uri.getSchemeSpecificPart();
688 if (pkgName != null) {
689 pkgList = new String[] { pkgName };
690 }
691 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
692 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
693 } else if (Intent.ACTION_MEDIA_RESOURCES_AVAILABLE.equals(action)) {
694 added = true;
695 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
696 } else if (Intent.ACTION_MEDIA_RESOURCES_UNAVAILABLE.equals(action)) {
697 added = false;
698 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
699 }
700 if (pkgList == null || pkgList.length == 0) {
701 return;
702 }
703 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700704 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800705 for (String pkgName : pkgList) {
706 if (replacing) {
707 // The package was just upgraded
708 updatePackageParticipantsLocked(pkgName);
709 } else {
710 // The package was just added
711 addPackageParticipantsLocked(pkgName);
712 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700713 }
714 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800715 } else {
716 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700717 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
718 } else {
719 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800720 for (String pkgName : pkgList) {
721 removePackageParticipantsLocked(pkgName);
722 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700723 }
724 }
725 }
726 }
727 };
728
Dan Egnor87a02bc2009-06-17 02:30:10 -0700729 // ----- Track connection to GoogleBackupTransport service -----
730 ServiceConnection mGoogleConnection = new ServiceConnection() {
731 public void onServiceConnected(ComponentName name, IBinder service) {
732 if (DEBUG) Log.v(TAG, "Connected to Google transport");
733 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700734 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700735 }
736
737 public void onServiceDisconnected(ComponentName name) {
738 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
739 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700740 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700741 }
742 };
743
Christopher Tate181fafa2009-05-14 11:12:14 -0700744 // Add the backup agents in the given package to our set of known backup participants.
745 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700746 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700747 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700748 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700749 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700750 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700751 }
752
Christopher Tate181fafa2009-05-14 11:12:14 -0700753 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700754 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700755 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700756 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
757 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700758 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700759 + " uid=" + p.applicationInfo.uid
760 + " killAfterRestore="
761 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
762 + " restoreNeedsApplication="
763 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
764 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700765 }
766 }
767
Dan Egnorefe52642009-06-24 00:16:33 -0700768 for (PackageInfo pkg : targetPkgs) {
769 if (packageName == null || pkg.packageName.equals(packageName)) {
770 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700771 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700772 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700773 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700774 mBackupParticipants.put(uid, set);
775 }
Dan Egnorefe52642009-06-24 00:16:33 -0700776 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700777
778 // If we've never seen this app before, schedule a backup for it
779 if (!mEverStoredApps.contains(pkg.packageName)) {
780 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
781 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700782 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700783 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700784 }
Christopher Tate487529a2009-04-29 14:03:25 -0700785 }
786 }
787
Christopher Tate6785dd82009-06-18 15:58:25 -0700788 // Remove the given package's entry from our known active set. If
789 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700790 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700791 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700792 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700793 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700794 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700795 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700796 int flags = PackageManager.GET_SIGNATURES;
797 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700798 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700799 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700800 }
801 } else {
802 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700803 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700804 }
805 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700806 }
807
Joe Onorato8ad02812009-05-13 01:41:44 -0400808 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700809 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700810 if (DEBUG) {
811 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
812 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700813 for (PackageInfo p : agents) {
814 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700815 }
816 }
Dan Egnorefe52642009-06-24 00:16:33 -0700817 for (PackageInfo pkg : agents) {
818 if (packageName == null || pkg.packageName.equals(packageName)) {
819 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700820 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700821 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700822 // Find the existing entry with the same package name, and remove it.
823 // We can't just remove(app) because the instances are different.
824 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700825 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700826 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700827 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700828 break;
829 }
830 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700831 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700832 mBackupParticipants.delete(uid);
833 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700834 }
835 }
836 }
837 }
838
Christopher Tate181fafa2009-05-14 11:12:14 -0700839 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700840 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700841 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700842 int flags = PackageManager.GET_SIGNATURES;
843 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
844 int N = packages.size();
845 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700846 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700847 try {
848 ApplicationInfo app = pkg.applicationInfo;
849 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
850 || app.backupAgentName == null
851 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
852 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
853 packages.remove(a);
854 }
855 else {
856 // we will need the shared library path, so look that up and store it here
857 app = mPackageManager.getApplicationInfo(pkg.packageName,
858 PackageManager.GET_SHARED_LIBRARY_FILES);
859 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
860 }
861 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700862 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700863 }
864 }
Dan Egnorefe52642009-06-24 00:16:33 -0700865 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700866 }
Christopher Tateaa088442009-06-16 18:25:46 -0700867
Christopher Tate3799bc22009-05-06 16:13:56 -0700868 // Reset the given package's known backup participants. Unlike add/remove, the update
869 // action cannot be passed a null package name.
870 void updatePackageParticipantsLocked(String packageName) {
871 if (packageName == null) {
872 Log.e(TAG, "updatePackageParticipants called with null package name");
873 return;
874 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700875 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700876
877 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700878 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700879 removePackageParticipantsLockedInner(packageName, allApps);
880 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700881 }
882
Christopher Tate73e02522009-07-15 14:18:26 -0700883 // Called from the backup thread: record that the given app has been successfully
884 // backed up at least once
885 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700886 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
887
888 synchronized (mEverStoredApps) {
889 if (!mEverStoredApps.add(packageName)) return;
890
891 RandomAccessFile out = null;
892 try {
893 out = new RandomAccessFile(mEverStored, "rws");
894 out.seek(out.length());
895 out.writeUTF(packageName);
896 } catch (IOException e) {
897 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
898 } finally {
899 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700900 }
901 }
902 }
903
Christopher Tatee97e8072009-07-15 16:45:50 -0700904 // Remove our awareness of having ever backed up the given package
905 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700906 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700907
Dan Egnor852f8e42009-09-30 11:20:45 -0700908 synchronized (mEverStoredApps) {
909 // Rewrite the file and rename to overwrite. If we reboot in the middle,
910 // we'll recognize on initialization time that the package no longer
911 // exists and fix it up then.
912 File tempKnownFile = new File(mBaseStateDir, "processed.new");
913 RandomAccessFile known = null;
914 try {
915 known = new RandomAccessFile(tempKnownFile, "rws");
916 mEverStoredApps.remove(packageName);
917 for (String s : mEverStoredApps) {
918 known.writeUTF(s);
919 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700920 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700921 known.close();
922 known = null;
923 if (!tempKnownFile.renameTo(mEverStored)) {
924 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
925 }
926 } catch (IOException e) {
927 // Bad: we couldn't create the new copy. For safety's sake we
928 // abandon the whole process and remove all what's-backed-up
929 // state entirely, meaning we'll force a backup pass for every
930 // participant on the next boot or [re]install.
931 Log.w(TAG, "Error rewriting " + mEverStored, e);
932 mEverStoredApps.clear();
933 tempKnownFile.delete();
934 mEverStored.delete();
935 } finally {
936 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700937 }
938 }
939 }
940
Dan Egnor87a02bc2009-06-17 02:30:10 -0700941 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700942 private IBackupTransport getTransport(String transportName) {
943 synchronized (mTransports) {
944 IBackupTransport transport = mTransports.get(transportName);
945 if (transport == null) {
946 Log.w(TAG, "Requested unavailable transport: " + transportName);
947 }
948 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700949 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700950 }
951
Christopher Tatedf01dea2009-06-09 20:45:02 -0700952 // fire off a backup agent, blocking until it attaches or times out
953 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
954 IBackupAgent agent = null;
955 synchronized(mAgentConnectLock) {
956 mConnecting = true;
957 mConnectedAgent = null;
958 try {
959 if (mActivityManager.bindBackupAgent(app, mode)) {
960 Log.d(TAG, "awaiting agent for " + app);
961
962 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700963 // only wait 10 seconds for the clear data to happen
964 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
965 while (mConnecting && mConnectedAgent == null
966 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700967 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700968 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700969 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700970 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700971 return null;
972 }
973 }
974
975 // if we timed out with no connect, abort and move on
976 if (mConnecting == true) {
977 Log.w(TAG, "Timeout waiting for agent " + app);
978 return null;
979 }
980 agent = mConnectedAgent;
981 }
982 } catch (RemoteException e) {
983 // can't happen
984 }
985 }
986 return agent;
987 }
988
Christopher Tatec7b31e32009-06-10 15:49:30 -0700989 // clear an application's data, blocking until the operation completes or times out
990 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700991 // Don't wipe packages marked allowClearUserData=false
992 try {
993 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
994 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
995 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
996 + packageName);
997 return;
998 }
999 } catch (NameNotFoundException e) {
1000 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
1001 return;
1002 }
1003
Christopher Tatec7b31e32009-06-10 15:49:30 -07001004 ClearDataObserver observer = new ClearDataObserver();
1005
1006 synchronized(mClearDataLock) {
1007 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001008 /* This is causing some critical processes to be killed during setup.
1009 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -07001010 try {
1011 mActivityManager.clearApplicationUserData(packageName, observer);
1012 } catch (RemoteException e) {
1013 // can't happen because the activity manager is in this process
1014 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001015 */
1016 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001017
1018 // only wait 10 seconds for the clear data to happen
1019 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1020 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1021 try {
1022 mClearDataLock.wait(5000);
1023 } catch (InterruptedException e) {
1024 // won't happen, but still.
1025 mClearingData = false;
1026 }
1027 }
1028 }
1029 }
1030
1031 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001032 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001033 synchronized(mClearDataLock) {
1034 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001035 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001036 }
1037 }
1038 }
1039
Christopher Tate44a27902010-01-27 17:15:49 -08001040 // -----
1041 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1042 boolean waitUntilOperationComplete(int token) {
1043 int finalState = OP_PENDING;
1044 synchronized (mCurrentOpLock) {
1045 try {
1046 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1047 try {
1048 mCurrentOpLock.wait();
1049 } catch (InterruptedException e) {}
1050 }
1051 } catch (IndexOutOfBoundsException e) {
1052 // the operation has been mysteriously cleared from our
1053 // bookkeeping -- consider this a success and ignore it.
1054 }
1055 }
1056 mBackupHandler.removeMessages(MSG_TIMEOUT);
1057 if (DEBUG) Log.v(TAG, "operation " + token + " complete: finalState=" + finalState);
1058 return finalState == OP_ACKNOWLEDGED;
1059 }
1060
1061 void prepareOperationTimeout(int token, long interval) {
1062 if (DEBUG) Log.v(TAG, "starting timeout: token=" + token + " interval=" + interval);
1063 mCurrentOperations.put(token, OP_PENDING);
1064 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1065 mBackupHandler.sendMessageDelayed(msg, interval);
1066 }
1067
Christopher Tate043dadc2009-06-02 16:11:00 -07001068 // ----- Back up a set of applications via a worker thread -----
1069
Christopher Tate44a27902010-01-27 17:15:49 -08001070 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001071 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001072 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001073 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001074 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001075 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001076
Christopher Tate44a27902010-01-27 17:15:49 -08001077 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001078 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001079 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001080 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001081 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001082
1083 try {
1084 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1085 } catch (RemoteException e) {
1086 // can't happen; the transport is local
1087 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001088 }
1089
Christopher Tate043dadc2009-06-02 16:11:00 -07001090 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001091 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001092 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001093 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1094
Christopher Tate79588342009-06-30 16:11:49 -07001095 // Backups run at background priority
1096 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1097
Christopher Tate043dadc2009-06-02 16:11:00 -07001098 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001099 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001100
Dan Egnor852f8e42009-09-30 11:20:45 -07001101 // If we haven't stored package manager metadata yet, we must init the transport.
1102 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1103 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1104 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1105 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001106 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001107 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001108 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001109 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001110 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Dan Egnor726247c2009-09-29 19:12:31 -07001111 Log.e(TAG, "Transport error in initializeDevice()");
1112 }
Dan Egnor01445162009-09-21 17:04:05 -07001113 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001114
1115 // The package manager doesn't have a proper <application> etc, but since
1116 // it's running here in the system process we can just set up its agent
1117 // directly and use a synthetic BackupRequest. We always run this pass
1118 // because it's cheap and this way we guarantee that we don't get out of
1119 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001120 if (status == BackupConstants.TRANSPORT_OK) {
1121 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1122 mPackageManager, allAgentPackages());
1123 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1124 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1125 status = processOneBackup(pmRequest,
1126 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1127 }
Christopher Tate90967f42009-09-20 15:28:33 -07001128
Dan Egnor01445162009-09-21 17:04:05 -07001129 if (status == BackupConstants.TRANSPORT_OK) {
1130 // Now run all the backups in our queue
1131 status = doQueuedBackups(mTransport);
1132 }
1133
1134 if (status == BackupConstants.TRANSPORT_OK) {
1135 // Tell the transport to finish everything it has buffered
1136 status = mTransport.finishBackup();
1137 if (status == BackupConstants.TRANSPORT_OK) {
1138 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001139 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001140 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001141 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001142 Log.e(TAG, "Transport error in finishBackup()");
1143 }
1144 }
1145
Dan Egnor01445162009-09-21 17:04:05 -07001146 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001147 // The backend reports that our dataset has been wiped. We need to
1148 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001149 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001150 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001151 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001152 }
1153 } catch (Exception e) {
1154 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001155 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001156 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001157 // If things went wrong, we need to re-stage the apps we had expected
1158 // to be backing up in this pass. This journals the package names in
1159 // the current active pending-backup file, not in the we are holding
1160 // here in mJournal.
1161 if (status != BackupConstants.TRANSPORT_OK) {
1162 Log.w(TAG, "Backup pass unsuccessful, restaging");
1163 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001164 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001165 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001166
1167 // We also want to reset the backup schedule based on whatever
1168 // the transport suggests by way of retry/backoff time.
1169 try {
1170 startBackupAlarmsLocked(mTransport.requestBackupTime());
1171 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001172 }
1173
1174 // Either backup was successful, in which case we of course do not need
1175 // this pass's journal any more; or it failed, in which case we just
1176 // re-enqueued all of these packages in the current active journal.
1177 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001178 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001179 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1180 }
1181
Christopher Tatec2af5d32010-02-02 15:18:58 -08001182 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001183 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001184 backupNow();
1185 }
1186
Dan Egnorbb9001c2009-07-27 12:20:13 -07001187 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001188 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001189 }
1190
Dan Egnor01445162009-09-21 17:04:05 -07001191 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001192 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001193 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001194
Christopher Tate0749dcd2009-08-13 15:13:03 -07001195 // Don't run backup, even if requested, if the target app does not have
1196 // the requisite permission
1197 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1198 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1199 Log.w(TAG, "Skipping backup of unprivileged package "
1200 + request.appInfo.packageName);
1201 continue;
1202 }
1203
Christopher Tate043dadc2009-06-02 16:11:00 -07001204 IBackupAgent agent = null;
1205 int mode = (request.fullBackup)
1206 ? IApplicationThread.BACKUP_MODE_FULL
1207 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1208 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001209 agent = bindToAgentSynchronous(request.appInfo, mode);
1210 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001211 int result = processOneBackup(request, agent, transport);
1212 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001213 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001214 } catch (SecurityException ex) {
1215 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001216 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001217 } finally {
1218 try { // unbind even on timeout, just in case
1219 mActivityManager.unbindBackupAgent(request.appInfo);
1220 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001221 }
1222 }
Dan Egnor01445162009-09-21 17:04:05 -07001223
1224 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001225 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001226
Dan Egnor01445162009-09-21 17:04:05 -07001227 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1228 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001229 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001230 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001231
Dan Egnorbb9001c2009-07-27 12:20:13 -07001232 File savedStateName = new File(mStateDir, packageName);
1233 File backupDataName = new File(mDataDir, packageName + ".data");
1234 File newStateName = new File(mStateDir, packageName + ".new");
1235
1236 ParcelFileDescriptor savedState = null;
1237 ParcelFileDescriptor backupData = null;
1238 ParcelFileDescriptor newState = null;
1239
1240 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001241 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001242 try {
1243 // Look up the package info & signatures. This is first so that if it
1244 // throws an exception, there's no file setup yet that would need to
1245 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001246 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1247 // The metadata 'package' is synthetic
1248 packInfo = new PackageInfo();
1249 packInfo.packageName = packageName;
1250 } else {
1251 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001252 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001253 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001254
Christopher Tatec7b31e32009-06-10 15:49:30 -07001255 // In a full backup, we pass a null ParcelFileDescriptor as
1256 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001257 if (!request.fullBackup) {
1258 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001259 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001260 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1261 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001262
Dan Egnorbb9001c2009-07-27 12:20:13 -07001263 backupData = ParcelFileDescriptor.open(backupDataName,
1264 ParcelFileDescriptor.MODE_READ_WRITE |
1265 ParcelFileDescriptor.MODE_CREATE |
1266 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001267
Dan Egnorbb9001c2009-07-27 12:20:13 -07001268 newState = ParcelFileDescriptor.open(newStateName,
1269 ParcelFileDescriptor.MODE_READ_WRITE |
1270 ParcelFileDescriptor.MODE_CREATE |
1271 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001272
Christopher Tate44a27902010-01-27 17:15:49 -08001273 // Initiate the target's backup pass
1274 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1275 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1276 boolean success = waitUntilOperationComplete(token);
1277
1278 if (!success) {
1279 // timeout -- bail out into the failed-transaction logic
1280 throw new RuntimeException("Backup timeout");
1281 }
1282
Dan Egnorbb9001c2009-07-27 12:20:13 -07001283 logBackupComplete(packageName);
1284 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001285 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001286 Log.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001287 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001288 backupDataName.delete();
1289 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001290 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001291 } finally {
1292 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1293 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1294 try { if (newState != null) newState.close(); } catch (IOException e) {}
1295 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001296 synchronized (mCurrentOpLock) {
1297 mCurrentOperations.clear();
1298 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001299 }
1300
1301 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001302 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001303 try {
1304 int size = (int) backupDataName.length();
1305 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001306 if (result == BackupConstants.TRANSPORT_OK) {
1307 backupData = ParcelFileDescriptor.open(backupDataName,
1308 ParcelFileDescriptor.MODE_READ_ONLY);
1309 result = transport.performBackup(packInfo, backupData);
1310 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001311
Dan Egnor83861e72009-09-17 16:17:55 -07001312 // TODO - We call finishBackup() for each application backed up, because
1313 // we need to know now whether it succeeded or failed. Instead, we should
1314 // hold off on finishBackup() until the end, which implies holding off on
1315 // renaming *all* the output state files (see below) until that happens.
1316
Dan Egnor01445162009-09-21 17:04:05 -07001317 if (result == BackupConstants.TRANSPORT_OK) {
1318 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001319 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001320 } else {
1321 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1322 }
1323
1324 // After successful transport, delete the now-stale data
1325 // and juggle the files so that next time we supply the agent
1326 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001327 if (result == BackupConstants.TRANSPORT_OK) {
1328 backupDataName.delete();
1329 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001330 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001331 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001332 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001333 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001334 } catch (Exception e) {
1335 Log.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001336 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001337 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001338 } finally {
1339 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001340 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001341
Dan Egnor01445162009-09-21 17:04:05 -07001342 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001343 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001344 }
1345
Christopher Tatedf01dea2009-06-09 20:45:02 -07001346
1347 // ----- Restore handling -----
1348
Christopher Tate78dd4a72009-11-04 11:49:08 -08001349 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1350 // If the target resides on the system partition, we allow it to restore
1351 // data from the like-named package in a restore set even if the signatures
1352 // do not match. (Unlike general applications, those flashed to the system
1353 // partition will be signed with the device's platform certificate, so on
1354 // different phones the same system app will have different signatures.)
1355 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1356 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1357 return true;
1358 }
1359
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001360 // Allow unsigned apps, but not signed on one device and unsigned on the other
1361 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001362 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001363 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1364 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001365 if ((storedSigs == null || storedSigs.length == 0)
1366 && (deviceSigs == null || deviceSigs.length == 0)) {
1367 return true;
1368 }
1369 if (storedSigs == null || deviceSigs == null) {
1370 return false;
1371 }
1372
Christopher Tateabce4e82009-06-18 18:35:32 -07001373 // !!! TODO: this demands that every stored signature match one
1374 // that is present on device, and does not demand the converse.
1375 // Is this this right policy?
1376 int nStored = storedSigs.length;
1377 int nDevice = deviceSigs.length;
1378
1379 for (int i=0; i < nStored; i++) {
1380 boolean match = false;
1381 for (int j=0; j < nDevice; j++) {
1382 if (storedSigs[i].equals(deviceSigs[j])) {
1383 match = true;
1384 break;
1385 }
1386 }
1387 if (!match) {
1388 return false;
1389 }
1390 }
1391 return true;
1392 }
1393
Christopher Tate44a27902010-01-27 17:15:49 -08001394 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001395 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001396 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001397 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001398 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001399
Christopher Tate5cbbf562009-06-22 16:44:51 -07001400 class RestoreRequest {
1401 public PackageInfo app;
1402 public int storedAppVersion;
1403
1404 RestoreRequest(PackageInfo _app, int _version) {
1405 app = _app;
1406 storedAppVersion = _version;
1407 }
1408 }
1409
Christopher Tate44a27902010-01-27 17:15:49 -08001410 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001411 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001412 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001413 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001414 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001415 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001416
1417 try {
1418 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1419 } catch (RemoteException e) {
1420 // can't happen; the transport is local
1421 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001422 }
1423
Christopher Tatedf01dea2009-06-09 20:45:02 -07001424 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001425 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001426 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001427 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001428 /**
1429 * Restore sequence:
1430 *
Dan Egnorefe52642009-06-24 00:16:33 -07001431 * 1. get the restore set description for our identity
1432 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001433 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001434 * 3. for each app in the restore queue:
1435 * 3.a. clear the app data
1436 * 3.b. get the restore data for the app from the transport
1437 * 3.c. launch the backup agent for the app
1438 * 3.d. agent.doRestore() with the data from the server
1439 * 3.e. unbind the agent [and kill the app?]
1440 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001441 *
1442 * On errors, we try our best to recover and move on to the next
1443 * application, but if necessary we abort the whole operation --
1444 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001445 */
1446
Christopher Tate7d562ec2009-06-25 18:03:43 -07001447 int error = -1; // assume error
1448
Dan Egnorefe52642009-06-24 00:16:33 -07001449 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001450 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001451 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001453
Dan Egnorefe52642009-06-24 00:16:33 -07001454 // Get the list of all packages which have backup enabled.
1455 // (Include the Package Manager metadata pseudo-package first.)
1456 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1457 PackageInfo omPackage = new PackageInfo();
1458 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1459 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001460
Dan Egnorefe52642009-06-24 00:16:33 -07001461 List<PackageInfo> agentPackages = allAgentPackages();
1462 restorePackages.addAll(agentPackages);
1463
Christopher Tate7d562ec2009-06-25 18:03:43 -07001464 // let the observer know that we're running
1465 if (mObserver != null) {
1466 try {
1467 // !!! TODO: get an actual count from the transport after
1468 // its startRestore() runs?
1469 mObserver.restoreStarting(restorePackages.size());
1470 } catch (RemoteException e) {
1471 Log.d(TAG, "Restore observer died at restoreStarting");
1472 mObserver = null;
1473 }
1474 }
1475
Dan Egnor01445162009-09-21 17:04:05 -07001476 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1477 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001478 Log.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001479 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001480 return;
1481 }
1482
1483 String packageName = mTransport.nextRestorePackage();
1484 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001485 Log.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001486 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001487 return;
1488 } else if (packageName.equals("")) {
1489 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001490 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001491 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001492 return;
1493 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1494 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1495 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001496 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001497 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001498 return;
1499 }
1500
1501 // Pull the Package Manager metadata from the restore set first
1502 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1503 mPackageManager, agentPackages);
1504 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1505
Christopher Tate8c032472009-07-02 14:28:47 -07001506 // Verify that the backup set includes metadata. If not, we can't do
1507 // signature/version verification etc, so we simply do not proceed with
1508 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001509 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001510 Log.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001511 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001512 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001513 return;
1514 }
1515
Christopher Tate7d562ec2009-06-25 18:03:43 -07001516 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001517 for (;;) {
1518 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001519
Dan Egnorefe52642009-06-24 00:16:33 -07001520 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001521 Log.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001522 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001523 return;
1524 } else if (packageName.equals("")) {
1525 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001526 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001527
Christopher Tate7d562ec2009-06-25 18:03:43 -07001528 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001529 try {
1530 mObserver.onUpdate(count);
1531 } catch (RemoteException e) {
1532 Log.d(TAG, "Restore observer died in onUpdate");
1533 mObserver = null;
1534 }
1535 }
1536
Dan Egnorefe52642009-06-24 00:16:33 -07001537 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1538 if (metaInfo == null) {
1539 Log.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001540 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001541 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001542 continue;
1543 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001544
Dan Egnorbb9001c2009-07-27 12:20:13 -07001545 PackageInfo packageInfo;
1546 try {
1547 int flags = PackageManager.GET_SIGNATURES;
1548 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1549 } catch (NameNotFoundException e) {
1550 Log.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001551 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001552 "Package missing on device");
1553 continue;
1554 }
1555
Dan Egnorefe52642009-06-24 00:16:33 -07001556 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001557 String message = "Version " + metaInfo.versionCode
1558 + " > installed version " + packageInfo.versionCode;
1559 Log.w(TAG, "Package " + packageName + ": " + message);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001560 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001561 continue;
1562 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001563
Christopher Tate78dd4a72009-11-04 11:49:08 -08001564 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001565 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001566 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001567 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001568 continue;
1569 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001570
Dan Egnorefe52642009-06-24 00:16:33 -07001571 if (DEBUG) Log.v(TAG, "Package " + packageName
1572 + " restore version [" + metaInfo.versionCode
1573 + "] is compatible with installed version ["
1574 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001575
Christopher Tate5e1ab332009-09-01 20:32:49 -07001576 // Now perform the actual restore: first clear the app's data
1577 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001578 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001579
1580 // Then set up and bind the agent (with a restricted Application object
1581 // unless the application says otherwise)
1582 boolean useRealApp = (packageInfo.applicationInfo.flags
1583 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1584 if (DEBUG && useRealApp) {
1585 Log.v(TAG, "agent requires real Application subclass for restore");
1586 }
Dan Egnorefe52642009-06-24 00:16:33 -07001587 IBackupAgent agent = bindToAgentSynchronous(
1588 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001589 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1590 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001591 if (agent == null) {
1592 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001593 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001594 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001595 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001596 }
1597
Christopher Tate5e1ab332009-09-01 20:32:49 -07001598 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001599 try {
1600 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001601 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001602 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001603 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001604 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001605
1606 // The agent was probably running with a stub Application object,
1607 // which isn't a valid run mode for the main app logic. Shut
1608 // down the app so that next time it's launched, it gets the
1609 // usual full initialization.
1610 if ((packageInfo.applicationInfo.flags
1611 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1612 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1613 + packageInfo.applicationInfo.processName);
1614 mActivityManager.killApplicationProcess(
1615 packageInfo.applicationInfo.processName,
1616 packageInfo.applicationInfo.uid);
1617 }
Dan Egnorefe52642009-06-24 00:16:33 -07001618 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001619 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001620
1621 // if we get this far, report success to the observer
1622 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001623 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001624 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001625 } catch (Exception e) {
1626 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001627 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001628 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1629
Dan Egnorefe52642009-06-24 00:16:33 -07001630 try {
1631 mTransport.finishRestore();
1632 } catch (RemoteException e) {
1633 Log.e(TAG, "Error finishing restore", e);
1634 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001635
1636 if (mObserver != null) {
1637 try {
1638 mObserver.restoreFinished(error);
1639 } catch (RemoteException e) {
1640 Log.d(TAG, "Restore observer died at restoreFinished");
1641 }
1642 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001643
1644 // done; we can finally release the wakelock
1645 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001646 }
1647 }
1648
Dan Egnorefe52642009-06-24 00:16:33 -07001649 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1650 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001651 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001652 final String packageName = app.packageName;
1653
Dan Egnorbb9001c2009-07-27 12:20:13 -07001654 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001655
Christopher Tate0749dcd2009-08-13 15:13:03 -07001656 // Don't restore to unprivileged packages
1657 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1658 packageName) != PackageManager.PERMISSION_GRANTED) {
1659 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1660 }
1661
Christopher Tatec7b31e32009-06-10 15:49:30 -07001662 // !!! TODO: get the dirs from the transport
1663 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001664 File newStateName = new File(mStateDir, packageName + ".new");
1665 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001666
Dan Egnorbb9001c2009-07-27 12:20:13 -07001667 ParcelFileDescriptor backupData = null;
1668 ParcelFileDescriptor newState = null;
1669
Christopher Tate44a27902010-01-27 17:15:49 -08001670 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001671 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001672 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001673 backupData = ParcelFileDescriptor.open(backupDataName,
1674 ParcelFileDescriptor.MODE_READ_WRITE |
1675 ParcelFileDescriptor.MODE_CREATE |
1676 ParcelFileDescriptor.MODE_TRUNCATE);
1677
Dan Egnor01445162009-09-21 17:04:05 -07001678 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001679 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001680 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001681 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001682 }
1683
1684 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001685 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001686 backupData = ParcelFileDescriptor.open(backupDataName,
1687 ParcelFileDescriptor.MODE_READ_ONLY);
1688
Dan Egnorbb9001c2009-07-27 12:20:13 -07001689 newState = ParcelFileDescriptor.open(newStateName,
1690 ParcelFileDescriptor.MODE_READ_WRITE |
1691 ParcelFileDescriptor.MODE_CREATE |
1692 ParcelFileDescriptor.MODE_TRUNCATE);
1693
Christopher Tate44a27902010-01-27 17:15:49 -08001694 // Kick off the restore, checking for hung agents
1695 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1696 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1697 boolean success = waitUntilOperationComplete(token);
1698
1699 if (!success) {
1700 throw new RuntimeException("restore timeout");
1701 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001702
1703 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001704 //
1705 // !!! TODO: the restored data should be migrated on the server
1706 // side into the current dataset. In that case the new state file
1707 // we just created would reflect the data already extant in the
1708 // backend, so there'd be nothing more to do. Until that happens,
1709 // however, we need to make sure that we record the data to the
1710 // current backend dataset. (Yes, this means shipping the data over
1711 // the wire in both directions. That's bad, but consistency comes
1712 // first, then efficiency.) Once we introduce server-side data
1713 // migration to the newly-restored device's dataset, we will change
1714 // the following from a discard of the newly-written state to the
1715 // "correct" operation of renaming into the canonical state blob.
1716 newStateName.delete(); // TODO: remove; see above comment
1717 //newStateName.renameTo(savedStateName); // TODO: replace with this
1718
Dan Egnorbb9001c2009-07-27 12:20:13 -07001719 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001720 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001721 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001722 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001723 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001724
Christopher Tate96733042009-07-20 14:49:13 -07001725 // If the agent fails restore, it might have put the app's data
1726 // into an incoherent state. For consistency we wipe its data
1727 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001728 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001729 } finally {
1730 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001731 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1732 try { if (newState != null) newState.close(); } catch (IOException e) {}
1733 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001734 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001735 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001736 }
1737 }
1738
Christopher Tate44a27902010-01-27 17:15:49 -08001739 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001740 IBackupTransport mTransport;
1741 PackageInfo mPackage;
1742
Christopher Tate44a27902010-01-27 17:15:49 -08001743 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001744 mTransport = transport;
1745 mPackage = packageInfo;
1746 }
1747
Christopher Tateee0e78a2009-07-02 11:17:03 -07001748 public void run() {
1749 try {
1750 // Clear the on-device backup state to ensure a full backup next time
1751 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1752 File stateFile = new File(stateDir, mPackage.packageName);
1753 stateFile.delete();
1754
1755 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001756 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001757 mTransport.clearBackupData(mPackage);
1758 } catch (RemoteException e) {
1759 // can't happen; the transport is local
1760 } finally {
1761 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001762 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001763 mTransport.finishBackup();
1764 } catch (RemoteException e) {
1765 // can't happen; the transport is local
1766 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001767
1768 // Last but not least, release the cpu
1769 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001770 }
1771 }
1772 }
1773
Christopher Tate44a27902010-01-27 17:15:49 -08001774 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001775 HashSet<String> mQueue;
1776
Christopher Tate44a27902010-01-27 17:15:49 -08001777 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001778 mQueue = transportNames;
1779 }
1780
Christopher Tate4cc86e12009-09-21 19:36:51 -07001781 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001782 try {
1783 for (String transportName : mQueue) {
1784 IBackupTransport transport = getTransport(transportName);
1785 if (transport == null) {
1786 Log.e(TAG, "Requested init for " + transportName + " but not found");
1787 continue;
1788 }
1789
Dan Egnor726247c2009-09-29 19:12:31 -07001790 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001791 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001792 long startRealtime = SystemClock.elapsedRealtime();
1793 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001794
Christopher Tate4cc86e12009-09-21 19:36:51 -07001795 if (status == BackupConstants.TRANSPORT_OK) {
1796 status = transport.finishBackup();
1797 }
1798
1799 // Okay, the wipe really happened. Clean up our local bookkeeping.
1800 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001801 Log.i(TAG, "Device init successful");
1802 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001803 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001804 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001805 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001806 synchronized (mQueueLock) {
1807 recordInitPendingLocked(false, transportName);
1808 }
Dan Egnor726247c2009-09-29 19:12:31 -07001809 } else {
1810 // If this didn't work, requeue this one and try again
1811 // after a suitable interval
1812 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001813 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001814 synchronized (mQueueLock) {
1815 recordInitPendingLocked(true, transportName);
1816 }
1817 // do this via another alarm to make sure of the wakelock states
1818 long delay = transport.requestBackupTime();
1819 if (DEBUG) Log.w(TAG, "init failed on "
1820 + transportName + " resched in " + delay);
1821 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1822 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001823 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001824 }
1825 } catch (RemoteException e) {
1826 // can't happen; the transports are local
1827 } catch (Exception e) {
1828 Log.e(TAG, "Unexpected error performing init", e);
1829 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001830 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001831 mWakelock.release();
1832 }
1833 }
1834 }
1835
Christopher Tatedf01dea2009-06-09 20:45:02 -07001836
Christopher Tate487529a2009-04-29 14:03:25 -07001837 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001838
Dan Egnor852f8e42009-09-30 11:20:45 -07001839 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001840 // Record that we need a backup pass for the caller. Since multiple callers
1841 // may share a uid, we need to note all candidates within that uid and schedule
1842 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001843 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001844
Christopher Tate63d27002009-06-16 17:16:42 -07001845 // If the caller does not hold the BACKUP permission, it can only request a
1846 // backup of its own data.
1847 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001848 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001849 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1850 targets = mBackupParticipants.get(Binder.getCallingUid());
1851 } else {
1852 // a caller with full permission can ask to back up any participating app
1853 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001854 targets = new HashSet<ApplicationInfo>();
1855 int N = mBackupParticipants.size();
1856 for (int i = 0; i < N; i++) {
1857 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1858 if (s != null) {
1859 targets.addAll(s);
1860 }
1861 }
1862 }
Christopher Tate487529a2009-04-29 14:03:25 -07001863 if (targets != null) {
1864 synchronized (mQueueLock) {
1865 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001866 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001867 // validate the caller-supplied package name against the known set of
1868 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001869 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001870 // Add the caller to the set of pending backups. If there is
1871 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001872 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001873 if (mPendingBackups.put(app, req) == null) {
1874 // Journal this request in case of crash. The put()
1875 // operation returned null when this package was not already
1876 // in the set; we want to avoid touching the disk redundantly.
1877 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001878
Christopher Tate22b60d82009-07-07 16:36:02 -07001879 if (DEBUG) {
1880 int numKeys = mPendingBackups.size();
1881 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1882 for (BackupRequest b : mPendingBackups.values()) {
1883 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1884 }
1885 }
1886 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001887 }
1888 }
Christopher Tate487529a2009-04-29 14:03:25 -07001889 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001890 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001891 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1892 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001893 }
1894 }
Christopher Tate46758122009-05-06 11:22:00 -07001895
Christopher Tatecde87f42009-06-12 12:55:53 -07001896 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001897 RandomAccessFile out = null;
1898 try {
1899 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1900 out = new RandomAccessFile(mJournal, "rws");
1901 out.seek(out.length());
1902 out.writeUTF(str);
1903 } catch (IOException e) {
1904 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1905 mJournal = null;
1906 } finally {
1907 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001908 }
1909 }
1910
Christopher Tateee0e78a2009-07-02 11:17:03 -07001911 // Clear the given package's backup data from the current transport
1912 public void clearBackupData(String packageName) {
1913 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1914 PackageInfo info;
1915 try {
1916 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1917 } catch (NameNotFoundException e) {
1918 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1919 return;
1920 }
1921
1922 // If the caller does not hold the BACKUP permission, it can only request a
1923 // wipe of its own backed-up data.
1924 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001925 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001926 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1927 apps = mBackupParticipants.get(Binder.getCallingUid());
1928 } else {
1929 // a caller with full permission can ask to back up any participating app
1930 // !!! TODO: allow data-clear of ANY app?
1931 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1932 apps = new HashSet<ApplicationInfo>();
1933 int N = mBackupParticipants.size();
1934 for (int i = 0; i < N; i++) {
1935 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1936 if (s != null) {
1937 apps.addAll(s);
1938 }
1939 }
1940 }
1941
1942 // now find the given package in the set of candidate apps
1943 for (ApplicationInfo app : apps) {
1944 if (app.packageName.equals(packageName)) {
1945 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1946 // found it; fire off the clear request
1947 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001948 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001949 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001950 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1951 new ClearParams(getTransport(mCurrentTransport), info));
1952 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001953 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001954 }
1955 break;
1956 }
1957 }
1958 }
1959
Christopher Tateace7f092009-06-15 18:07:25 -07001960 // Run a backup pass immediately for any applications that have declared
1961 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07001962 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04001963 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001964
Christopher Tateace7f092009-06-15 18:07:25 -07001965 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001966 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001967 // Because the alarms we are using can jitter, and we want an *immediate*
1968 // backup pass to happen, we restart the timer beginning with "next time,"
1969 // then manually fire the backup trigger intent ourselves.
1970 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001971 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001972 mRunBackupIntent.send();
1973 } catch (PendingIntent.CanceledException e) {
1974 // should never happen
1975 Log.e(TAG, "run-backup intent cancelled!");
1976 }
Christopher Tate46758122009-05-06 11:22:00 -07001977 }
1978 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001979
Christopher Tate8031a3d2009-07-06 16:36:05 -07001980 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001981 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001982 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1983 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001984
Christopher Tate4cc86e12009-09-21 19:36:51 -07001985 Log.i(TAG, "Backup enabled => " + enable);
1986
Christopher Tate6ef58a12009-06-29 14:56:28 -07001987 boolean wasEnabled = mEnabled;
1988 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001989 Settings.Secure.putInt(mContext.getContentResolver(),
1990 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001991 mEnabled = enable;
1992 }
1993
Christopher Tate49401dd2009-07-01 12:34:29 -07001994 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001995 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001996 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001997 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001998 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001999 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07002000 if (DEBUG) Log.i(TAG, "Opting out of backup");
2001
Christopher Tateb6787f22009-07-02 17:40:45 -07002002 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002003
2004 // This also constitutes an opt-out, so we wipe any data for
2005 // this device from the backend. We start that process with
2006 // an alarm in order to guarantee wakelock states.
2007 if (wasEnabled && mProvisioned) {
2008 // NOTE: we currently flush every registered transport, not just
2009 // the currently-active one.
2010 HashSet<String> allTransports;
2011 synchronized (mTransports) {
2012 allTransports = new HashSet<String>(mTransports.keySet());
2013 }
2014 // build the set of transports for which we are posting an init
2015 for (String transport : allTransports) {
2016 recordInitPendingLocked(true, transport);
2017 }
2018 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2019 mRunInitIntent);
2020 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002021 }
2022 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002023 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002024
Christopher Tatecce9da52010-02-03 15:11:15 -08002025 // Enable/disable automatic restore of app data at install time
2026 public void setAutoRestore(boolean doAutoRestore) {
2027 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2028 "setBackupEnabled");
2029
2030 Log.i(TAG, "Auto restore => " + doAutoRestore);
2031
2032 synchronized (this) {
2033 Settings.Secure.putInt(mContext.getContentResolver(),
2034 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2035 mAutoRestore = doAutoRestore;
2036 }
2037 }
2038
Christopher Tate8031a3d2009-07-06 16:36:05 -07002039 // Mark the backup service as having been provisioned
2040 public void setBackupProvisioned(boolean available) {
2041 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2042 "setBackupProvisioned");
2043
2044 boolean wasProvisioned = mProvisioned;
2045 synchronized (this) {
2046 Settings.Secure.putInt(mContext.getContentResolver(),
2047 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2048 mProvisioned = available;
2049 }
2050
2051 synchronized (mQueueLock) {
2052 if (available && !wasProvisioned && mEnabled) {
2053 // we're now good to go, so start the backup alarms
2054 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2055 } else if (!available) {
2056 // No longer enabled, so stop running backups
2057 Log.w(TAG, "Backup service no longer provisioned");
2058 mAlarmManager.cancel(mRunBackupIntent);
2059 }
2060 }
2061 }
2062
2063 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002064 // We used to use setInexactRepeating(), but that may be linked to
2065 // backups running at :00 more often than not, creating load spikes.
2066 // Schedule at an exact time for now, and also add a bit of "fuzz".
2067
2068 Random random = new Random();
2069 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2070 random.nextInt(FUZZ_MILLIS);
2071 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2072 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002073 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002074 }
2075
Christopher Tate6ef58a12009-06-29 14:56:28 -07002076 // Report whether the backup mechanism is currently enabled
2077 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002078 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002079 return mEnabled; // no need to synchronize just to read it
2080 }
2081
Christopher Tate91717492009-06-26 21:07:13 -07002082 // Report the name of the currently active transport
2083 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002084 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002085 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002086 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002087 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002088 }
2089
Christopher Tate91717492009-06-26 21:07:13 -07002090 // Report all known, available backup transports
2091 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002092 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002093
Christopher Tate91717492009-06-26 21:07:13 -07002094 String[] list = null;
2095 ArrayList<String> known = new ArrayList<String>();
2096 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2097 if (entry.getValue() != null) {
2098 known.add(entry.getKey());
2099 }
2100 }
2101
2102 if (known.size() > 0) {
2103 list = new String[known.size()];
2104 known.toArray(list);
2105 }
2106 return list;
2107 }
2108
2109 // Select which transport to use for the next backup operation. If the given
2110 // name is not one of the available transports, no action is taken and the method
2111 // returns null.
2112 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002113 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002114
2115 synchronized (mTransports) {
2116 String prevTransport = null;
2117 if (mTransports.get(transport) != null) {
2118 prevTransport = mCurrentTransport;
2119 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002120 Settings.Secure.putString(mContext.getContentResolver(),
2121 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002122 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2123 + " returning " + prevTransport);
2124 } else {
2125 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2126 }
2127 return prevTransport;
2128 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002129 }
2130
2131 // Callback: a requested backup agent has been instantiated. This should only
2132 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002133 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002134 synchronized(mAgentConnectLock) {
2135 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2136 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2137 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2138 mConnectedAgent = agent;
2139 mConnecting = false;
2140 } else {
2141 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2142 + " claiming agent connected");
2143 }
2144 mAgentConnectLock.notifyAll();
2145 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002146 }
2147
2148 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2149 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002150 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002151 public void agentDisconnected(String packageName) {
2152 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002153 synchronized(mAgentConnectLock) {
2154 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2155 mConnectedAgent = null;
2156 mConnecting = false;
2157 } else {
2158 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2159 + " claiming agent disconnected");
2160 }
2161 mAgentConnectLock.notifyAll();
2162 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002163 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002164
Christopher Tate8c850b72009-06-07 19:33:20 -07002165 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002166 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002167 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002168
2169 synchronized(this) {
2170 if (mActiveRestoreSession != null) {
2171 Log.d(TAG, "Restore session requested but one already active");
2172 return null;
2173 }
Christopher Tate80202c82010-01-25 19:37:47 -08002174 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002175 }
2176 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002177 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002178
Christopher Tate44a27902010-01-27 17:15:49 -08002179 // Note that a currently-active backup agent has notified us that it has
2180 // completed the given outstanding asynchronous backup/restore operation.
2181 public void opComplete(int token) {
2182 synchronized (mCurrentOpLock) {
2183 if (DEBUG) Log.v(TAG, "opComplete: " + token);
2184 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2185 mCurrentOpLock.notifyAll();
2186 }
2187 }
2188
Christopher Tate9b3905c2009-06-08 15:24:01 -07002189 // ----- Restore session -----
2190
Christopher Tate80202c82010-01-25 19:37:47 -08002191 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002192 private static final String TAG = "RestoreSession";
2193
Christopher Tate9b3905c2009-06-08 15:24:01 -07002194 private IBackupTransport mRestoreTransport = null;
2195 RestoreSet[] mRestoreSets = null;
2196
Christopher Tate80202c82010-01-25 19:37:47 -08002197 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002198 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002199 }
2200
2201 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002202 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002204 "getAvailableRestoreSets");
2205
Christopher Tatef68eb502009-06-16 11:02:01 -07002206 try {
Christopher Tate43383042009-07-13 15:17:13 -07002207 if (mRestoreTransport == null) {
2208 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002209 return null;
2210 }
2211 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002212 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002213 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002214 }
2215 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002216 } catch (Exception e) {
2217 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2218 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002219 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002220 }
2221
Dan Egnor0084da52009-07-29 12:57:16 -07002222 public synchronized int performRestore(long token, IRestoreObserver observer) {
2223 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2224 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002225
Christopher Tatef2c321a2009-08-10 15:43:36 -07002226 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2227 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002228
Dan Egnor0084da52009-07-29 12:57:16 -07002229 if (mRestoreTransport == null || mRestoreSets == null) {
2230 Log.e(TAG, "Ignoring performRestore() with no restore set");
2231 return -1;
2232 }
2233
Christopher Tate21ab6a52009-09-24 18:01:46 -07002234 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002235 for (int i = 0; i < mRestoreSets.length; i++) {
2236 if (token == mRestoreSets[i].token) {
2237 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002238 mWakelock.acquire();
2239 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2240 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2241 mBackupHandler.sendMessage(msg);
2242 Binder.restoreCallingIdentity(oldId);
2243 return 0;
2244 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002245 }
2246 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002247
2248 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002249 return -1;
2250 }
2251
Dan Egnor0084da52009-07-29 12:57:16 -07002252 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002254 "endRestoreSession");
2255
Dan Egnor0084da52009-07-29 12:57:16 -07002256 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002257
Dan Egnor0084da52009-07-29 12:57:16 -07002258 synchronized (this) {
2259 try {
2260 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2261 } catch (Exception e) {
2262 Log.e(TAG, "Error in finishRestore", e);
2263 } finally {
2264 mRestoreTransport = null;
2265 }
2266 }
2267
2268 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002269 if (BackupManagerService.this.mActiveRestoreSession == this) {
2270 BackupManagerService.this.mActiveRestoreSession = null;
2271 } else {
2272 Log.e(TAG, "ending non-current restore session");
2273 }
2274 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002275 }
2276 }
2277
Christopher Tate043dadc2009-06-02 16:11:00 -07002278
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002279 @Override
2280 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2281 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002282 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002283 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002284 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tate55f931a2009-09-29 17:17:34 -07002285 pw.println("Last backup pass: " + mLastBackupPass
2286 + " (now = " + System.currentTimeMillis() + ')');
2287 pw.println(" next scheduled: " + mNextBackupPass);
2288
Christopher Tate91717492009-06-26 21:07:13 -07002289 pw.println("Available transports:");
2290 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002291 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2292 try {
2293 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2294 for (File f : dir.listFiles()) {
2295 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2296 }
2297 } catch (RemoteException e) {
2298 Log.e(TAG, "Error in transportDirName()", e);
2299 pw.println(" Error: " + e);
2300 }
Christopher Tate91717492009-06-26 21:07:13 -07002301 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002302
2303 pw.println("Pending init: " + mPendingInits.size());
2304 for (String s : mPendingInits) {
2305 pw.println(" " + s);
2306 }
2307
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002308 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002309 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002310 for (int i=0; i<N; i++) {
2311 int uid = mBackupParticipants.keyAt(i);
2312 pw.print(" uid: ");
2313 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002314 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2315 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002316 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002317 }
2318 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002319
Christopher Tate73e02522009-07-15 14:18:26 -07002320 pw.println("Ever backed up: " + mEverStoredApps.size());
2321 for (String pkg : mEverStoredApps) {
2322 pw.println(" " + pkg);
2323 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002324
2325 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002326 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002327 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002328 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002329 }
2330 }
Christopher Tate487529a2009-04-29 14:03:25 -07002331}