blob: 62dcb0878f257166d659f13d9353d6238c11370d [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;
121 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800122 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
123 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700124 PendingIntent mRunBackupIntent, mRunInitIntent;
125 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700126 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700127 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700128 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700129 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700130 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700131 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700132 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700133
Christopher Tate181fafa2009-05-14 11:12:14 -0700134 BackupRequest(ApplicationInfo app, boolean isFull) {
135 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700136 fullBackup = isFull;
137 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700138
139 public String toString() {
140 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
141 }
Christopher Tate46758122009-05-06 11:22:00 -0700142 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400143 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700144 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700145 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700146
147 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700148 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700149
150 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700151 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700152
Christopher Tate043dadc2009-06-02 16:11:00 -0700153 // The thread performing the sequence of queued backups binds to each app's agent
154 // in succession. Bind notifications are asynchronously delivered through the
155 // Activity Manager; use this lock object to signal when a requested binding has
156 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700157 final Object mAgentConnectLock = new Object();
158 IBackupAgent mConnectedAgent;
159 volatile boolean mConnecting;
Christopher Tate21ab6a52009-09-24 18:01:46 -0700160 volatile boolean mBackupOrRestoreInProgress = false;
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 Tate21ab6a52009-09-24 18:01:46 -0700220 volatile boolean mInitInProgress = false;
Christopher Tateaa088442009-06-16 18:25:46 -0700221
Christopher Tate44a27902010-01-27 17:15:49 -0800222 // ----- Asynchronous backup/restore handler thread -----
223
224 private class BackupHandler extends Handler {
225 public BackupHandler(Looper looper) {
226 super(looper);
227 }
228
229 public void handleMessage(Message msg) {
230
231 switch (msg.what) {
232 case MSG_RUN_BACKUP:
233 {
234 mLastBackupPass = System.currentTimeMillis();
235 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
236
237 IBackupTransport transport = getTransport(mCurrentTransport);
238 if (transport == null) {
239 Log.v(TAG, "Backup requested but no transport available");
240 synchronized (mQueueLock) {
241 mBackupOrRestoreInProgress = false;
242 }
243 mWakelock.release();
244 break;
245 }
246
247 // snapshot the pending-backup set and work on that
248 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
249 synchronized (mQueueLock) {
250 // Do we have any work to do?
251 if (mPendingBackups.size() > 0) {
252 for (BackupRequest b: mPendingBackups.values()) {
253 queue.add(b);
254 }
255 if (DEBUG) Log.v(TAG, "clearing pending backups");
256 mPendingBackups.clear();
257
258 // Start a new backup-queue journal file too
259 File oldJournal = mJournal;
260 mJournal = null;
261
262 // At this point, we have started a new journal file, and the old
263 // file identity is being passed to the backup processing thread.
264 // When it completes successfully, that old journal file will be
265 // deleted. If we crash prior to that, the old journal is parsed
266 // at next boot and the journaled requests fulfilled.
267 (new PerformBackupTask(transport, queue, oldJournal)).run();
268 } else {
269 Log.v(TAG, "Backup requested but nothing pending");
270 synchronized (mQueueLock) {
271 mBackupOrRestoreInProgress = false;
272 }
273 mWakelock.release();
274 }
275 }
276 break;
277 }
278
279 case MSG_RUN_FULL_BACKUP:
280 break;
281
282 case MSG_RUN_RESTORE:
283 {
284 RestoreParams params = (RestoreParams)msg.obj;
285 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
286 (new PerformRestoreTask(params.transport, params.observer,
287 params.token)).run();
288 break;
289 }
290
291 case MSG_RUN_CLEAR:
292 {
293 ClearParams params = (ClearParams)msg.obj;
294 (new PerformClearTask(params.transport, params.packageInfo)).run();
295 break;
296 }
297
298 case MSG_RUN_INITIALIZE:
299 {
300 HashSet<String> queue;
301
302 // Snapshot the pending-init queue and work on that
303 synchronized (mQueueLock) {
304 queue = new HashSet<String>(mPendingInits);
305 mPendingInits.clear();
306 }
307
308 (new PerformInitializeTask(queue)).run();
309 break;
310 }
311
312 case MSG_TIMEOUT:
313 {
314 synchronized (mCurrentOpLock) {
315 final int token = msg.arg1;
316 int state = mCurrentOperations.get(token, OP_TIMEOUT);
317 if (state == OP_PENDING) {
318 if (DEBUG) Log.v(TAG, "TIMEOUT: token=" + token);
319 mCurrentOperations.put(token, OP_TIMEOUT);
320 }
321 mCurrentOpLock.notifyAll();
322 }
323 break;
324 }
325 }
326 }
327 }
328
329 // ----- Main service implementation -----
330
Christopher Tate487529a2009-04-29 14:03:25 -0700331 public BackupManagerService(Context context) {
332 mContext = context;
333 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700334 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700335
Christopher Tateb6787f22009-07-02 17:40:45 -0700336 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
337 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
338
Christopher Tate44a27902010-01-27 17:15:49 -0800339 mBackupManagerBinder = asInterface(asBinder());
340
341 // spin up the backup/restore handler thread
342 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
343 mHandlerThread.start();
344 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
345
Christopher Tate22b87872009-05-04 16:41:53 -0700346 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700347 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700348 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700349 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700350 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800351 // If Encrypted file systems is enabled or disabled, this call will return the
352 // correct directory.
353 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
354 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700355 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700356
Christopher Tate4cc86e12009-09-21 19:36:51 -0700357 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700358 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700359 IntentFilter filter = new IntentFilter();
360 filter.addAction(RUN_BACKUP_ACTION);
361 context.registerReceiver(mRunBackupReceiver, filter,
362 android.Manifest.permission.BACKUP, null);
363
364 mRunInitReceiver = new RunInitializeReceiver();
365 filter = new IntentFilter();
366 filter.addAction(RUN_INITIALIZE_ACTION);
367 context.registerReceiver(mRunInitReceiver, filter,
368 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700369
370 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700371 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
372 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
373
Christopher Tate4cc86e12009-09-21 19:36:51 -0700374 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
375 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
376 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
377
Christopher Tatecde87f42009-06-12 12:55:53 -0700378 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700379 mJournalDir = new File(mBaseStateDir, "pending");
380 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700381 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700382
Christopher Tate73e02522009-07-15 14:18:26 -0700383 // Set up the various sorts of package tracking we do
384 initPackageTracking();
385
Christopher Tateabce4e82009-06-18 18:35:32 -0700386 // Build our mapping of uid to backup client services. This implicitly
387 // schedules a backup pass on the Package Manager metadata the first
388 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700389 synchronized (mBackupParticipants) {
390 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700391 }
392
Dan Egnor87a02bc2009-06-17 02:30:10 -0700393 // Set up our transport options and initialize the default transport
394 // TODO: Have transports register themselves somehow?
395 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700396 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700397 ComponentName localName = new ComponentName(context, LocalTransport.class);
398 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700399
Christopher Tate91717492009-06-26 21:07:13 -0700400 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700401 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
402 Settings.Secure.BACKUP_TRANSPORT);
403 if ("".equals(mCurrentTransport)) {
404 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700405 }
Christopher Tate91717492009-06-26 21:07:13 -0700406 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
407
408 // Attach to the Google backup transport. When this comes up, it will set
409 // itself as the current transport because we explicitly reset mCurrentTransport
410 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700411 Intent intent = new Intent().setComponent(new ComponentName(
412 "com.google.android.backup",
413 "com.google.android.backup.BackupTransportService"));
414 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700415
Christopher Tatecde87f42009-06-12 12:55:53 -0700416 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700417 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700418 parseLeftoverJournals();
419
Christopher Tateb6787f22009-07-02 17:40:45 -0700420 // Power management
421 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
422
423 // Start the backup passes going
424 setBackupEnabled(areEnabled);
425 }
426
427 private class RunBackupReceiver extends BroadcastReceiver {
428 public void onReceive(Context context, Intent intent) {
429 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700430 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700431 if (mPendingInits.size() > 0) {
432 // If there are pending init operations, we process those
433 // and then settle into the usual periodic backup schedule.
434 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
435 try {
436 mAlarmManager.cancel(mRunInitIntent);
437 mRunInitIntent.send();
438 } catch (PendingIntent.CanceledException ce) {
439 Log.e(TAG, "Run init intent cancelled");
440 // can't really do more than bail here
441 }
442 } else {
443 // Don't run backups now if we're disabled, not yet
Christopher Tate21ab6a52009-09-24 18:01:46 -0700444 // fully set up, in the middle of a backup already,
445 // or racing with an initialize pass.
446 if (mEnabled && mProvisioned
447 && !mBackupOrRestoreInProgress && !mInitInProgress) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700448 if (DEBUG) Log.v(TAG, "Running a backup pass");
Christopher Tate21ab6a52009-09-24 18:01:46 -0700449 mBackupOrRestoreInProgress = true;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700450
451 // Acquire the wakelock and pass it to the backup thread. it will
452 // be released once backup concludes.
453 mWakelock.acquire();
454
455 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
456 mBackupHandler.sendMessage(msg);
457 } else {
458 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned
Christopher Tate21ab6a52009-09-24 18:01:46 -0700459 + " b=" + mBackupOrRestoreInProgress + " i=" + mInitInProgress);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700460 }
461 }
462 }
463 }
464 }
465 }
466
467 private class RunInitializeReceiver extends BroadcastReceiver {
468 public void onReceive(Context context, Intent intent) {
469 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
470 synchronized (mQueueLock) {
471 if (DEBUG) Log.v(TAG, "Running a device init");
472 mInitInProgress = true;
473
474 // Acquire the wakelock and pass it to the init thread. it will
475 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700476 mWakelock.acquire();
477
Christopher Tate4cc86e12009-09-21 19:36:51 -0700478 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700479 mBackupHandler.sendMessage(msg);
480 }
481 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700482 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700483 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700484
Christopher Tate73e02522009-07-15 14:18:26 -0700485 private void initPackageTracking() {
486 if (DEBUG) Log.v(TAG, "Initializing package tracking");
487
Christopher Tatee97e8072009-07-15 16:45:50 -0700488 // Keep a log of what apps we've ever backed up. Because we might have
489 // rebooted in the middle of an operation that was removing something from
490 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700491 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700492 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700493
Christopher Tatee97e8072009-07-15 16:45:50 -0700494 // If we were in the middle of removing something from the ever-backed-up
495 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700496 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700497 if (tempProcessedFile.exists()) {
498 tempProcessedFile.delete();
499 }
500
Dan Egnor852f8e42009-09-30 11:20:45 -0700501 // If there are previous contents, parse them out then start a new
502 // file to continue the recordkeeping.
503 if (mEverStored.exists()) {
504 RandomAccessFile temp = null;
505 RandomAccessFile in = null;
506
507 try {
508 temp = new RandomAccessFile(tempProcessedFile, "rws");
509 in = new RandomAccessFile(mEverStored, "r");
510
511 while (true) {
512 PackageInfo info;
513 String pkg = in.readUTF();
514 try {
515 info = mPackageManager.getPackageInfo(pkg, 0);
516 mEverStoredApps.add(pkg);
517 temp.writeUTF(pkg);
518 if (DEBUG) Log.v(TAG, " + " + pkg);
519 } catch (NameNotFoundException e) {
520 // nope, this package was uninstalled; don't include it
521 if (DEBUG) Log.v(TAG, " - " + pkg);
522 }
523 }
524 } catch (EOFException e) {
525 // Once we've rewritten the backup history log, atomically replace the
526 // old one with the new one then reopen the file for continuing use.
527 if (!tempProcessedFile.renameTo(mEverStored)) {
528 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
529 }
530 } catch (IOException e) {
531 Log.e(TAG, "Error in processed file", e);
532 } finally {
533 try { if (temp != null) temp.close(); } catch (IOException e) {}
534 try { if (in != null) in.close(); } catch (IOException e) {}
535 }
536 }
537
Christopher Tate73e02522009-07-15 14:18:26 -0700538 // Register for broadcasts about package install, etc., so we can
539 // update the provider list.
540 IntentFilter filter = new IntentFilter();
541 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
542 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
543 filter.addDataScheme("package");
544 mContext.registerReceiver(mBroadcastReceiver, filter);
545 }
546
Christopher Tatecde87f42009-06-12 12:55:53 -0700547 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700548 for (File f : mJournalDir.listFiles()) {
549 if (mJournal == null || f.compareTo(mJournal) != 0) {
550 // This isn't the current journal, so it must be a leftover. Read
551 // out the package names mentioned there and schedule them for
552 // backup.
553 RandomAccessFile in = null;
554 try {
555 Log.i(TAG, "Found stale backup journal, scheduling:");
556 in = new RandomAccessFile(f, "r");
557 while (true) {
558 String packageName = in.readUTF();
559 Log.i(TAG, " + " + packageName);
560 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700561 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700562 } catch (EOFException e) {
563 // no more data; we're done
564 } catch (Exception e) {
565 Log.e(TAG, "Can't read " + f, e);
566 } finally {
567 // close/delete the file
568 try { if (in != null) in.close(); } catch (IOException e) {}
569 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700570 }
571 }
572 }
573 }
574
Christopher Tate4cc86e12009-09-21 19:36:51 -0700575 // Maintain persistent state around whether need to do an initialize operation.
576 // Must be called with the queue lock held.
577 void recordInitPendingLocked(boolean isPending, String transportName) {
578 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
579 + " on transport " + transportName);
580 try {
581 IBackupTransport transport = getTransport(transportName);
582 String transportDirName = transport.transportDirName();
583 File stateDir = new File(mBaseStateDir, transportDirName);
584 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
585
586 if (isPending) {
587 // We need an init before we can proceed with sending backup data.
588 // Record that with an entry in our set of pending inits, as well as
589 // journaling it via creation of a sentinel file.
590 mPendingInits.add(transportName);
591 try {
592 (new FileOutputStream(initPendingFile)).close();
593 } catch (IOException ioe) {
594 // Something is badly wrong with our permissions; just try to move on
595 }
596 } else {
597 // No more initialization needed; wipe the journal and reset our state.
598 initPendingFile.delete();
599 mPendingInits.remove(transportName);
600 }
601 } catch (RemoteException e) {
602 // can't happen; the transport is local
603 }
604 }
605
Christopher Tated55e18a2009-09-21 10:12:59 -0700606 // Reset all of our bookkeeping, in response to having been told that
607 // the backend data has been wiped [due to idle expiry, for example],
608 // so we must re-upload all saved settings.
609 void resetBackupState(File stateFileDir) {
610 synchronized (mQueueLock) {
611 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700612 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700613 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700614
615 // Remove all the state files
616 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700617 // ... but don't touch the needs-init sentinel
618 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
619 sf.delete();
620 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700621 }
622
623 // Enqueue a new backup of every participant
624 int N = mBackupParticipants.size();
625 for (int i=0; i<N; i++) {
626 int uid = mBackupParticipants.keyAt(i);
627 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
628 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700629 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700630 }
631 }
632 }
633 }
634
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800635 // Add a transport to our set of available backends. If 'transport' is null, this
636 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700637 private void registerTransport(String name, IBackupTransport transport) {
638 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700639 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800640 if (transport != null) {
641 mTransports.put(name, transport);
642 } else {
643 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800644 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800645 mCurrentTransport = null;
646 }
647 // Nothing further to do in the unregistration case
648 return;
649 }
Christopher Tate91717492009-06-26 21:07:13 -0700650 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700651
652 // If the init sentinel file exists, we need to be sure to perform the init
653 // as soon as practical. We also create the state directory at registration
654 // time to ensure it's present from the outset.
655 try {
656 String transportName = transport.transportDirName();
657 File stateDir = new File(mBaseStateDir, transportName);
658 stateDir.mkdirs();
659
660 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
661 if (initSentinel.exists()) {
662 synchronized (mQueueLock) {
663 mPendingInits.add(transportName);
664
665 // TODO: pick a better starting time than now + 1 minute
666 long delay = 1000 * 60; // one minute, in milliseconds
667 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
668 System.currentTimeMillis() + delay, mRunInitIntent);
669 }
670 }
671 } catch (RemoteException e) {
672 // can't happen, the transport is local
673 }
Christopher Tate91717492009-06-26 21:07:13 -0700674 }
675
Christopher Tate3799bc22009-05-06 16:13:56 -0700676 // ----- Track installation/removal of packages -----
677 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
678 public void onReceive(Context context, Intent intent) {
679 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
680
681 Uri uri = intent.getData();
682 if (uri == null) {
683 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700684 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700685 String pkgName = uri.getSchemeSpecificPart();
686 if (pkgName == null) {
687 return;
688 }
689
690 String action = intent.getAction();
691 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
692 synchronized (mBackupParticipants) {
693 Bundle extras = intent.getExtras();
694 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
695 // The package was just upgraded
696 updatePackageParticipantsLocked(pkgName);
697 } else {
698 // The package was just added
699 addPackageParticipantsLocked(pkgName);
700 }
701 }
702 }
703 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
704 Bundle extras = intent.getExtras();
705 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
706 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
707 } else {
708 synchronized (mBackupParticipants) {
709 removePackageParticipantsLocked(pkgName);
710 }
711 }
712 }
713 }
714 };
715
Dan Egnor87a02bc2009-06-17 02:30:10 -0700716 // ----- Track connection to GoogleBackupTransport service -----
717 ServiceConnection mGoogleConnection = new ServiceConnection() {
718 public void onServiceConnected(ComponentName name, IBinder service) {
719 if (DEBUG) Log.v(TAG, "Connected to Google transport");
720 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700721 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700722 }
723
724 public void onServiceDisconnected(ComponentName name) {
725 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
726 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700727 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700728 }
729 };
730
Christopher Tate181fafa2009-05-14 11:12:14 -0700731 // Add the backup agents in the given package to our set of known backup participants.
732 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700733 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700734 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700735 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700736 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700737 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700738 }
739
Christopher Tate181fafa2009-05-14 11:12:14 -0700740 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700741 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700742 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700743 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
744 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700745 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700746 + " uid=" + p.applicationInfo.uid
747 + " killAfterRestore="
748 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
749 + " restoreNeedsApplication="
750 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
751 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700752 }
753 }
754
Dan Egnorefe52642009-06-24 00:16:33 -0700755 for (PackageInfo pkg : targetPkgs) {
756 if (packageName == null || pkg.packageName.equals(packageName)) {
757 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700758 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700759 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700760 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700761 mBackupParticipants.put(uid, set);
762 }
Dan Egnorefe52642009-06-24 00:16:33 -0700763 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700764
765 // If we've never seen this app before, schedule a backup for it
766 if (!mEverStoredApps.contains(pkg.packageName)) {
767 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
768 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700769 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700770 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700771 }
Christopher Tate487529a2009-04-29 14:03:25 -0700772 }
773 }
774
Christopher Tate6785dd82009-06-18 15:58:25 -0700775 // Remove the given package's entry from our known active set. If
776 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700777 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700778 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700779 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700780 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700781 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700782 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700783 int flags = PackageManager.GET_SIGNATURES;
784 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700785 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700786 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700787 }
788 } else {
789 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700790 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700791 }
792 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700793 }
794
Joe Onorato8ad02812009-05-13 01:41:44 -0400795 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700796 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700797 if (DEBUG) {
798 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
799 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700800 for (PackageInfo p : agents) {
801 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700802 }
803 }
Dan Egnorefe52642009-06-24 00:16:33 -0700804 for (PackageInfo pkg : agents) {
805 if (packageName == null || pkg.packageName.equals(packageName)) {
806 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700807 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700808 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700809 // Find the existing entry with the same package name, and remove it.
810 // We can't just remove(app) because the instances are different.
811 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700812 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700813 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700814 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700815 break;
816 }
817 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700818 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700819 mBackupParticipants.delete(uid);
820 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700821 }
822 }
823 }
824 }
825
Christopher Tate181fafa2009-05-14 11:12:14 -0700826 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700827 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700828 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700829 int flags = PackageManager.GET_SIGNATURES;
830 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
831 int N = packages.size();
832 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700833 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700834 try {
835 ApplicationInfo app = pkg.applicationInfo;
836 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
837 || app.backupAgentName == null
838 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
839 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
840 packages.remove(a);
841 }
842 else {
843 // we will need the shared library path, so look that up and store it here
844 app = mPackageManager.getApplicationInfo(pkg.packageName,
845 PackageManager.GET_SHARED_LIBRARY_FILES);
846 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
847 }
848 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700849 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700850 }
851 }
Dan Egnorefe52642009-06-24 00:16:33 -0700852 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700853 }
Christopher Tateaa088442009-06-16 18:25:46 -0700854
Christopher Tate3799bc22009-05-06 16:13:56 -0700855 // Reset the given package's known backup participants. Unlike add/remove, the update
856 // action cannot be passed a null package name.
857 void updatePackageParticipantsLocked(String packageName) {
858 if (packageName == null) {
859 Log.e(TAG, "updatePackageParticipants called with null package name");
860 return;
861 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700862 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700863
864 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700865 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700866 removePackageParticipantsLockedInner(packageName, allApps);
867 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700868 }
869
Christopher Tate73e02522009-07-15 14:18:26 -0700870 // Called from the backup thread: record that the given app has been successfully
871 // backed up at least once
872 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700873 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
874
875 synchronized (mEverStoredApps) {
876 if (!mEverStoredApps.add(packageName)) return;
877
878 RandomAccessFile out = null;
879 try {
880 out = new RandomAccessFile(mEverStored, "rws");
881 out.seek(out.length());
882 out.writeUTF(packageName);
883 } catch (IOException e) {
884 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
885 } finally {
886 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700887 }
888 }
889 }
890
Christopher Tatee97e8072009-07-15 16:45:50 -0700891 // Remove our awareness of having ever backed up the given package
892 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700893 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700894
Dan Egnor852f8e42009-09-30 11:20:45 -0700895 synchronized (mEverStoredApps) {
896 // Rewrite the file and rename to overwrite. If we reboot in the middle,
897 // we'll recognize on initialization time that the package no longer
898 // exists and fix it up then.
899 File tempKnownFile = new File(mBaseStateDir, "processed.new");
900 RandomAccessFile known = null;
901 try {
902 known = new RandomAccessFile(tempKnownFile, "rws");
903 mEverStoredApps.remove(packageName);
904 for (String s : mEverStoredApps) {
905 known.writeUTF(s);
906 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700907 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700908 known.close();
909 known = null;
910 if (!tempKnownFile.renameTo(mEverStored)) {
911 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
912 }
913 } catch (IOException e) {
914 // Bad: we couldn't create the new copy. For safety's sake we
915 // abandon the whole process and remove all what's-backed-up
916 // state entirely, meaning we'll force a backup pass for every
917 // participant on the next boot or [re]install.
918 Log.w(TAG, "Error rewriting " + mEverStored, e);
919 mEverStoredApps.clear();
920 tempKnownFile.delete();
921 mEverStored.delete();
922 } finally {
923 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700924 }
925 }
926 }
927
Dan Egnor87a02bc2009-06-17 02:30:10 -0700928 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700929 private IBackupTransport getTransport(String transportName) {
930 synchronized (mTransports) {
931 IBackupTransport transport = mTransports.get(transportName);
932 if (transport == null) {
933 Log.w(TAG, "Requested unavailable transport: " + transportName);
934 }
935 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700936 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700937 }
938
Christopher Tatedf01dea2009-06-09 20:45:02 -0700939 // fire off a backup agent, blocking until it attaches or times out
940 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
941 IBackupAgent agent = null;
942 synchronized(mAgentConnectLock) {
943 mConnecting = true;
944 mConnectedAgent = null;
945 try {
946 if (mActivityManager.bindBackupAgent(app, mode)) {
947 Log.d(TAG, "awaiting agent for " + app);
948
949 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700950 // only wait 10 seconds for the clear data to happen
951 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
952 while (mConnecting && mConnectedAgent == null
953 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700954 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700955 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700956 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700957 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700958 return null;
959 }
960 }
961
962 // if we timed out with no connect, abort and move on
963 if (mConnecting == true) {
964 Log.w(TAG, "Timeout waiting for agent " + app);
965 return null;
966 }
967 agent = mConnectedAgent;
968 }
969 } catch (RemoteException e) {
970 // can't happen
971 }
972 }
973 return agent;
974 }
975
Christopher Tatec7b31e32009-06-10 15:49:30 -0700976 // clear an application's data, blocking until the operation completes or times out
977 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700978 // Don't wipe packages marked allowClearUserData=false
979 try {
980 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
981 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
982 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
983 + packageName);
984 return;
985 }
986 } catch (NameNotFoundException e) {
987 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
988 return;
989 }
990
Christopher Tatec7b31e32009-06-10 15:49:30 -0700991 ClearDataObserver observer = new ClearDataObserver();
992
993 synchronized(mClearDataLock) {
994 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700995 /* This is causing some critical processes to be killed during setup.
996 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700997 try {
998 mActivityManager.clearApplicationUserData(packageName, observer);
999 } catch (RemoteException e) {
1000 // can't happen because the activity manager is in this process
1001 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -07001002 */
1003 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001004
1005 // only wait 10 seconds for the clear data to happen
1006 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1007 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1008 try {
1009 mClearDataLock.wait(5000);
1010 } catch (InterruptedException e) {
1011 // won't happen, but still.
1012 mClearingData = false;
1013 }
1014 }
1015 }
1016 }
1017
1018 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001019 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001020 synchronized(mClearDataLock) {
1021 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001022 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001023 }
1024 }
1025 }
1026
Christopher Tate44a27902010-01-27 17:15:49 -08001027 // -----
1028 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1029 boolean waitUntilOperationComplete(int token) {
1030 int finalState = OP_PENDING;
1031 synchronized (mCurrentOpLock) {
1032 try {
1033 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1034 try {
1035 mCurrentOpLock.wait();
1036 } catch (InterruptedException e) {}
1037 }
1038 } catch (IndexOutOfBoundsException e) {
1039 // the operation has been mysteriously cleared from our
1040 // bookkeeping -- consider this a success and ignore it.
1041 }
1042 }
1043 mBackupHandler.removeMessages(MSG_TIMEOUT);
1044 if (DEBUG) Log.v(TAG, "operation " + token + " complete: finalState=" + finalState);
1045 return finalState == OP_ACKNOWLEDGED;
1046 }
1047
1048 void prepareOperationTimeout(int token, long interval) {
1049 if (DEBUG) Log.v(TAG, "starting timeout: token=" + token + " interval=" + interval);
1050 mCurrentOperations.put(token, OP_PENDING);
1051 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1052 mBackupHandler.sendMessageDelayed(msg, interval);
1053 }
1054
Christopher Tate043dadc2009-06-02 16:11:00 -07001055 // ----- Back up a set of applications via a worker thread -----
1056
Christopher Tate44a27902010-01-27 17:15:49 -08001057 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001058 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001059 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001060 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001061 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001062 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001063
Christopher Tate44a27902010-01-27 17:15:49 -08001064 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001065 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001066 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001067 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001068 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001069
1070 try {
1071 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1072 } catch (RemoteException e) {
1073 // can't happen; the transport is local
1074 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001075 }
1076
Christopher Tate043dadc2009-06-02 16:11:00 -07001077 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001078 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001079 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001080 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1081
Christopher Tate79588342009-06-30 16:11:49 -07001082 // Backups run at background priority
1083 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1084
Christopher Tate043dadc2009-06-02 16:11:00 -07001085 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001086 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001087
Dan Egnor852f8e42009-09-30 11:20:45 -07001088 // If we haven't stored package manager metadata yet, we must init the transport.
1089 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1090 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1091 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1092 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001093 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001094 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001095 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001096 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001097 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Dan Egnor726247c2009-09-29 19:12:31 -07001098 Log.e(TAG, "Transport error in initializeDevice()");
1099 }
Dan Egnor01445162009-09-21 17:04:05 -07001100 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001101
1102 // The package manager doesn't have a proper <application> etc, but since
1103 // it's running here in the system process we can just set up its agent
1104 // directly and use a synthetic BackupRequest. We always run this pass
1105 // because it's cheap and this way we guarantee that we don't get out of
1106 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001107 if (status == BackupConstants.TRANSPORT_OK) {
1108 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1109 mPackageManager, allAgentPackages());
1110 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1111 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1112 status = processOneBackup(pmRequest,
1113 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1114 }
Christopher Tate90967f42009-09-20 15:28:33 -07001115
Dan Egnor01445162009-09-21 17:04:05 -07001116 if (status == BackupConstants.TRANSPORT_OK) {
1117 // Now run all the backups in our queue
1118 status = doQueuedBackups(mTransport);
1119 }
1120
1121 if (status == BackupConstants.TRANSPORT_OK) {
1122 // Tell the transport to finish everything it has buffered
1123 status = mTransport.finishBackup();
1124 if (status == BackupConstants.TRANSPORT_OK) {
1125 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001126 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001127 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001128 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001129 Log.e(TAG, "Transport error in finishBackup()");
1130 }
1131 }
1132
Dan Egnor01445162009-09-21 17:04:05 -07001133 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001134 // The backend reports that our dataset has been wiped. We need to
1135 // reset all of our bookkeeping and instead run a new backup pass for
Dan Egnor852f8e42009-09-30 11:20:45 -07001136 // everything. This must come after mBackupOrRestoreInProgress is cleared.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001137 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001138 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001139 }
1140 } catch (Exception e) {
1141 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001142 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001143 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001144 // If things went wrong, we need to re-stage the apps we had expected
1145 // to be backing up in this pass. This journals the package names in
1146 // the current active pending-backup file, not in the we are holding
1147 // here in mJournal.
1148 if (status != BackupConstants.TRANSPORT_OK) {
1149 Log.w(TAG, "Backup pass unsuccessful, restaging");
1150 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001151 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001152 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001153
1154 // We also want to reset the backup schedule based on whatever
1155 // the transport suggests by way of retry/backoff time.
1156 try {
1157 startBackupAlarmsLocked(mTransport.requestBackupTime());
1158 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001159 }
1160
1161 // Either backup was successful, in which case we of course do not need
1162 // this pass's journal any more; or it failed, in which case we just
1163 // re-enqueued all of these packages in the current active journal.
1164 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001165 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001166 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1167 }
1168
Christopher Tate21ab6a52009-09-24 18:01:46 -07001169 // Only once we're entirely finished do we indicate our completion
1170 // and release the wakelock
1171 synchronized (mQueueLock) {
1172 mBackupOrRestoreInProgress = false;
1173 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001174
1175 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
1176 // This must come after mBackupOrRestoreInProgress is cleared.
1177 backupNow();
1178 }
1179
Dan Egnorbb9001c2009-07-27 12:20:13 -07001180 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001181 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001182 }
1183
Dan Egnor01445162009-09-21 17:04:05 -07001184 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001185 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001186 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001187
Christopher Tate0749dcd2009-08-13 15:13:03 -07001188 // Don't run backup, even if requested, if the target app does not have
1189 // the requisite permission
1190 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1191 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1192 Log.w(TAG, "Skipping backup of unprivileged package "
1193 + request.appInfo.packageName);
1194 continue;
1195 }
1196
Christopher Tate043dadc2009-06-02 16:11:00 -07001197 IBackupAgent agent = null;
1198 int mode = (request.fullBackup)
1199 ? IApplicationThread.BACKUP_MODE_FULL
1200 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1201 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001202 agent = bindToAgentSynchronous(request.appInfo, mode);
1203 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001204 int result = processOneBackup(request, agent, transport);
1205 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001206 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001207 } catch (SecurityException ex) {
1208 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001209 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001210 } finally {
1211 try { // unbind even on timeout, just in case
1212 mActivityManager.unbindBackupAgent(request.appInfo);
1213 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001214 }
1215 }
Dan Egnor01445162009-09-21 17:04:05 -07001216
1217 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001218 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001219
Dan Egnor01445162009-09-21 17:04:05 -07001220 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1221 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001222 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001223 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001224
Dan Egnorbb9001c2009-07-27 12:20:13 -07001225 File savedStateName = new File(mStateDir, packageName);
1226 File backupDataName = new File(mDataDir, packageName + ".data");
1227 File newStateName = new File(mStateDir, packageName + ".new");
1228
1229 ParcelFileDescriptor savedState = null;
1230 ParcelFileDescriptor backupData = null;
1231 ParcelFileDescriptor newState = null;
1232
1233 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001234 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001235 try {
1236 // Look up the package info & signatures. This is first so that if it
1237 // throws an exception, there's no file setup yet that would need to
1238 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001239 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1240 // The metadata 'package' is synthetic
1241 packInfo = new PackageInfo();
1242 packInfo.packageName = packageName;
1243 } else {
1244 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001245 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001246 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001247
Christopher Tatec7b31e32009-06-10 15:49:30 -07001248 // In a full backup, we pass a null ParcelFileDescriptor as
1249 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001250 if (!request.fullBackup) {
1251 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001252 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001253 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1254 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001255
Dan Egnorbb9001c2009-07-27 12:20:13 -07001256 backupData = ParcelFileDescriptor.open(backupDataName,
1257 ParcelFileDescriptor.MODE_READ_WRITE |
1258 ParcelFileDescriptor.MODE_CREATE |
1259 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001260
Dan Egnorbb9001c2009-07-27 12:20:13 -07001261 newState = ParcelFileDescriptor.open(newStateName,
1262 ParcelFileDescriptor.MODE_READ_WRITE |
1263 ParcelFileDescriptor.MODE_CREATE |
1264 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001265
Christopher Tate44a27902010-01-27 17:15:49 -08001266 // Initiate the target's backup pass
1267 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1268 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1269 boolean success = waitUntilOperationComplete(token);
1270
1271 if (!success) {
1272 // timeout -- bail out into the failed-transaction logic
1273 throw new RuntimeException("Backup timeout");
1274 }
1275
Dan Egnorbb9001c2009-07-27 12:20:13 -07001276 logBackupComplete(packageName);
1277 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001278 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001279 Log.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001280 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001281 backupDataName.delete();
1282 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001283 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001284 } finally {
1285 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1286 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1287 try { if (newState != null) newState.close(); } catch (IOException e) {}
1288 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001289 synchronized (mCurrentOpLock) {
1290 mCurrentOperations.clear();
1291 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001292 }
1293
1294 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001295 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001296 try {
1297 int size = (int) backupDataName.length();
1298 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001299 if (result == BackupConstants.TRANSPORT_OK) {
1300 backupData = ParcelFileDescriptor.open(backupDataName,
1301 ParcelFileDescriptor.MODE_READ_ONLY);
1302 result = transport.performBackup(packInfo, backupData);
1303 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001304
Dan Egnor83861e72009-09-17 16:17:55 -07001305 // TODO - We call finishBackup() for each application backed up, because
1306 // we need to know now whether it succeeded or failed. Instead, we should
1307 // hold off on finishBackup() until the end, which implies holding off on
1308 // renaming *all* the output state files (see below) until that happens.
1309
Dan Egnor01445162009-09-21 17:04:05 -07001310 if (result == BackupConstants.TRANSPORT_OK) {
1311 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001312 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001313 } else {
1314 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1315 }
1316
1317 // After successful transport, delete the now-stale data
1318 // and juggle the files so that next time we supply the agent
1319 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001320 if (result == BackupConstants.TRANSPORT_OK) {
1321 backupDataName.delete();
1322 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001323 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001324 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001325 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001326 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001327 } catch (Exception e) {
1328 Log.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001329 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001330 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001331 } finally {
1332 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001333 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001334
Dan Egnor01445162009-09-21 17:04:05 -07001335 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001336 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001337 }
1338
Christopher Tatedf01dea2009-06-09 20:45:02 -07001339
1340 // ----- Restore handling -----
1341
Christopher Tate78dd4a72009-11-04 11:49:08 -08001342 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1343 // If the target resides on the system partition, we allow it to restore
1344 // data from the like-named package in a restore set even if the signatures
1345 // do not match. (Unlike general applications, those flashed to the system
1346 // partition will be signed with the device's platform certificate, so on
1347 // different phones the same system app will have different signatures.)
1348 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1349 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1350 return true;
1351 }
1352
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001353 // Allow unsigned apps, but not signed on one device and unsigned on the other
1354 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001355 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001356 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1357 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001358 if ((storedSigs == null || storedSigs.length == 0)
1359 && (deviceSigs == null || deviceSigs.length == 0)) {
1360 return true;
1361 }
1362 if (storedSigs == null || deviceSigs == null) {
1363 return false;
1364 }
1365
Christopher Tateabce4e82009-06-18 18:35:32 -07001366 // !!! TODO: this demands that every stored signature match one
1367 // that is present on device, and does not demand the converse.
1368 // Is this this right policy?
1369 int nStored = storedSigs.length;
1370 int nDevice = deviceSigs.length;
1371
1372 for (int i=0; i < nStored; i++) {
1373 boolean match = false;
1374 for (int j=0; j < nDevice; j++) {
1375 if (storedSigs[i].equals(deviceSigs[j])) {
1376 match = true;
1377 break;
1378 }
1379 }
1380 if (!match) {
1381 return false;
1382 }
1383 }
1384 return true;
1385 }
1386
Christopher Tate44a27902010-01-27 17:15:49 -08001387 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001388 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001389 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001390 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001391 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001392
Christopher Tate5cbbf562009-06-22 16:44:51 -07001393 class RestoreRequest {
1394 public PackageInfo app;
1395 public int storedAppVersion;
1396
1397 RestoreRequest(PackageInfo _app, int _version) {
1398 app = _app;
1399 storedAppVersion = _version;
1400 }
1401 }
1402
Christopher Tate44a27902010-01-27 17:15:49 -08001403 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001404 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001405 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001406 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001407 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001408 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001409
1410 try {
1411 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1412 } catch (RemoteException e) {
1413 // can't happen; the transport is local
1414 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001415 }
1416
Christopher Tatedf01dea2009-06-09 20:45:02 -07001417 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001418 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001419 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001420 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001421 /**
1422 * Restore sequence:
1423 *
Dan Egnorefe52642009-06-24 00:16:33 -07001424 * 1. get the restore set description for our identity
1425 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001426 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001427 * 3. for each app in the restore queue:
1428 * 3.a. clear the app data
1429 * 3.b. get the restore data for the app from the transport
1430 * 3.c. launch the backup agent for the app
1431 * 3.d. agent.doRestore() with the data from the server
1432 * 3.e. unbind the agent [and kill the app?]
1433 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001434 *
1435 * On errors, we try our best to recover and move on to the next
1436 * application, but if necessary we abort the whole operation --
1437 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001438 */
1439
Christopher Tate7d562ec2009-06-25 18:03:43 -07001440 int error = -1; // assume error
1441
Dan Egnorefe52642009-06-24 00:16:33 -07001442 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001443 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001444 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001446
Dan Egnorefe52642009-06-24 00:16:33 -07001447 // Get the list of all packages which have backup enabled.
1448 // (Include the Package Manager metadata pseudo-package first.)
1449 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1450 PackageInfo omPackage = new PackageInfo();
1451 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1452 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001453
Dan Egnorefe52642009-06-24 00:16:33 -07001454 List<PackageInfo> agentPackages = allAgentPackages();
1455 restorePackages.addAll(agentPackages);
1456
Christopher Tate7d562ec2009-06-25 18:03:43 -07001457 // let the observer know that we're running
1458 if (mObserver != null) {
1459 try {
1460 // !!! TODO: get an actual count from the transport after
1461 // its startRestore() runs?
1462 mObserver.restoreStarting(restorePackages.size());
1463 } catch (RemoteException e) {
1464 Log.d(TAG, "Restore observer died at restoreStarting");
1465 mObserver = null;
1466 }
1467 }
1468
Dan Egnor01445162009-09-21 17:04:05 -07001469 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1470 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001471 Log.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001473 return;
1474 }
1475
1476 String packageName = mTransport.nextRestorePackage();
1477 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001478 Log.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001479 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001480 return;
1481 } else if (packageName.equals("")) {
1482 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001483 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001484 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001485 return;
1486 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1487 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1488 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001489 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001490 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001491 return;
1492 }
1493
1494 // Pull the Package Manager metadata from the restore set first
1495 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1496 mPackageManager, agentPackages);
1497 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1498
Christopher Tate8c032472009-07-02 14:28:47 -07001499 // Verify that the backup set includes metadata. If not, we can't do
1500 // signature/version verification etc, so we simply do not proceed with
1501 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001502 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001503 Log.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001504 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001505 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001506 return;
1507 }
1508
Christopher Tate7d562ec2009-06-25 18:03:43 -07001509 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001510 for (;;) {
1511 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001512
Dan Egnorefe52642009-06-24 00:16:33 -07001513 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001514 Log.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001515 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001516 return;
1517 } else if (packageName.equals("")) {
1518 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001519 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001520
Christopher Tate7d562ec2009-06-25 18:03:43 -07001521 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001522 try {
1523 mObserver.onUpdate(count);
1524 } catch (RemoteException e) {
1525 Log.d(TAG, "Restore observer died in onUpdate");
1526 mObserver = null;
1527 }
1528 }
1529
Dan Egnorefe52642009-06-24 00:16:33 -07001530 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1531 if (metaInfo == null) {
1532 Log.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001533 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001534 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001535 continue;
1536 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001537
Dan Egnorbb9001c2009-07-27 12:20:13 -07001538 PackageInfo packageInfo;
1539 try {
1540 int flags = PackageManager.GET_SIGNATURES;
1541 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1542 } catch (NameNotFoundException e) {
1543 Log.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001544 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001545 "Package missing on device");
1546 continue;
1547 }
1548
Dan Egnorefe52642009-06-24 00:16:33 -07001549 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001550 String message = "Version " + metaInfo.versionCode
1551 + " > installed version " + packageInfo.versionCode;
1552 Log.w(TAG, "Package " + packageName + ": " + message);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001553 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001554 continue;
1555 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001556
Christopher Tate78dd4a72009-11-04 11:49:08 -08001557 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001558 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001559 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001560 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001561 continue;
1562 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001563
Dan Egnorefe52642009-06-24 00:16:33 -07001564 if (DEBUG) Log.v(TAG, "Package " + packageName
1565 + " restore version [" + metaInfo.versionCode
1566 + "] is compatible with installed version ["
1567 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001568
Christopher Tate5e1ab332009-09-01 20:32:49 -07001569 // Now perform the actual restore: first clear the app's data
1570 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001571 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001572
1573 // Then set up and bind the agent (with a restricted Application object
1574 // unless the application says otherwise)
1575 boolean useRealApp = (packageInfo.applicationInfo.flags
1576 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1577 if (DEBUG && useRealApp) {
1578 Log.v(TAG, "agent requires real Application subclass for restore");
1579 }
Dan Egnorefe52642009-06-24 00:16:33 -07001580 IBackupAgent agent = bindToAgentSynchronous(
1581 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001582 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1583 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001584 if (agent == null) {
1585 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001586 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001587 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001588 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001589 }
1590
Christopher Tate5e1ab332009-09-01 20:32:49 -07001591 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001592 try {
1593 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001594 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001595 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001596 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001597 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001598
1599 // The agent was probably running with a stub Application object,
1600 // which isn't a valid run mode for the main app logic. Shut
1601 // down the app so that next time it's launched, it gets the
1602 // usual full initialization.
1603 if ((packageInfo.applicationInfo.flags
1604 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1605 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1606 + packageInfo.applicationInfo.processName);
1607 mActivityManager.killApplicationProcess(
1608 packageInfo.applicationInfo.processName,
1609 packageInfo.applicationInfo.uid);
1610 }
Dan Egnorefe52642009-06-24 00:16:33 -07001611 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001612 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001613
1614 // if we get this far, report success to the observer
1615 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001616 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001617 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001618 } catch (Exception e) {
1619 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001620 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001621 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1622
Dan Egnorefe52642009-06-24 00:16:33 -07001623 try {
1624 mTransport.finishRestore();
1625 } catch (RemoteException e) {
1626 Log.e(TAG, "Error finishing restore", e);
1627 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001628
1629 if (mObserver != null) {
1630 try {
1631 mObserver.restoreFinished(error);
1632 } catch (RemoteException e) {
1633 Log.d(TAG, "Restore observer died at restoreFinished");
1634 }
1635 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001636
1637 // done; we can finally release the wakelock
Christopher Tate21ab6a52009-09-24 18:01:46 -07001638 synchronized (mQueueLock) {
1639 mBackupOrRestoreInProgress = false;
1640 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001641 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001642 }
1643 }
1644
Dan Egnorefe52642009-06-24 00:16:33 -07001645 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1646 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001647 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001648 final String packageName = app.packageName;
1649
Dan Egnorbb9001c2009-07-27 12:20:13 -07001650 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001651
Christopher Tate0749dcd2009-08-13 15:13:03 -07001652 // Don't restore to unprivileged packages
1653 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1654 packageName) != PackageManager.PERMISSION_GRANTED) {
1655 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1656 }
1657
Christopher Tatec7b31e32009-06-10 15:49:30 -07001658 // !!! TODO: get the dirs from the transport
1659 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001660 File newStateName = new File(mStateDir, packageName + ".new");
1661 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001662
Dan Egnorbb9001c2009-07-27 12:20:13 -07001663 ParcelFileDescriptor backupData = null;
1664 ParcelFileDescriptor newState = null;
1665
Christopher Tate44a27902010-01-27 17:15:49 -08001666 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001667 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001668 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001669 backupData = ParcelFileDescriptor.open(backupDataName,
1670 ParcelFileDescriptor.MODE_READ_WRITE |
1671 ParcelFileDescriptor.MODE_CREATE |
1672 ParcelFileDescriptor.MODE_TRUNCATE);
1673
Dan Egnor01445162009-09-21 17:04:05 -07001674 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001675 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001676 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001677 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001678 }
1679
1680 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001681 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001682 backupData = ParcelFileDescriptor.open(backupDataName,
1683 ParcelFileDescriptor.MODE_READ_ONLY);
1684
Dan Egnorbb9001c2009-07-27 12:20:13 -07001685 newState = ParcelFileDescriptor.open(newStateName,
1686 ParcelFileDescriptor.MODE_READ_WRITE |
1687 ParcelFileDescriptor.MODE_CREATE |
1688 ParcelFileDescriptor.MODE_TRUNCATE);
1689
Christopher Tate44a27902010-01-27 17:15:49 -08001690 // Kick off the restore, checking for hung agents
1691 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1692 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1693 boolean success = waitUntilOperationComplete(token);
1694
1695 if (!success) {
1696 throw new RuntimeException("restore timeout");
1697 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001698
1699 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001700 //
1701 // !!! TODO: the restored data should be migrated on the server
1702 // side into the current dataset. In that case the new state file
1703 // we just created would reflect the data already extant in the
1704 // backend, so there'd be nothing more to do. Until that happens,
1705 // however, we need to make sure that we record the data to the
1706 // current backend dataset. (Yes, this means shipping the data over
1707 // the wire in both directions. That's bad, but consistency comes
1708 // first, then efficiency.) Once we introduce server-side data
1709 // migration to the newly-restored device's dataset, we will change
1710 // the following from a discard of the newly-written state to the
1711 // "correct" operation of renaming into the canonical state blob.
1712 newStateName.delete(); // TODO: remove; see above comment
1713 //newStateName.renameTo(savedStateName); // TODO: replace with this
1714
Dan Egnorbb9001c2009-07-27 12:20:13 -07001715 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001716 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001717 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001718 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001719 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001720
Christopher Tate96733042009-07-20 14:49:13 -07001721 // If the agent fails restore, it might have put the app's data
1722 // into an incoherent state. For consistency we wipe its data
1723 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001724 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001725 } finally {
1726 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001727 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1728 try { if (newState != null) newState.close(); } catch (IOException e) {}
1729 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001730 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001731 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001732 }
1733 }
1734
Christopher Tate44a27902010-01-27 17:15:49 -08001735 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001736 IBackupTransport mTransport;
1737 PackageInfo mPackage;
1738
Christopher Tate44a27902010-01-27 17:15:49 -08001739 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001740 mTransport = transport;
1741 mPackage = packageInfo;
1742 }
1743
Christopher Tateee0e78a2009-07-02 11:17:03 -07001744 public void run() {
1745 try {
1746 // Clear the on-device backup state to ensure a full backup next time
1747 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1748 File stateFile = new File(stateDir, mPackage.packageName);
1749 stateFile.delete();
1750
1751 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001752 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001753 mTransport.clearBackupData(mPackage);
1754 } catch (RemoteException e) {
1755 // can't happen; the transport is local
1756 } finally {
1757 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001758 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001759 mTransport.finishBackup();
1760 } catch (RemoteException e) {
1761 // can't happen; the transport is local
1762 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001763
1764 // Last but not least, release the cpu
Christopher Tatea253f162009-09-27 15:16:44 -07001765 synchronized (mQueueLock) {
1766 mBackupOrRestoreInProgress = false;
1767 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001768 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001769 }
1770 }
1771 }
1772
Christopher Tate44a27902010-01-27 17:15:49 -08001773 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001774 HashSet<String> mQueue;
1775
Christopher Tate44a27902010-01-27 17:15:49 -08001776 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001777 mQueue = transportNames;
1778 }
1779
Christopher Tate4cc86e12009-09-21 19:36:51 -07001780 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001781 try {
1782 for (String transportName : mQueue) {
1783 IBackupTransport transport = getTransport(transportName);
1784 if (transport == null) {
1785 Log.e(TAG, "Requested init for " + transportName + " but not found");
1786 continue;
1787 }
1788
Dan Egnor726247c2009-09-29 19:12:31 -07001789 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001790 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001791 long startRealtime = SystemClock.elapsedRealtime();
1792 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001793
Christopher Tate4cc86e12009-09-21 19:36:51 -07001794 if (status == BackupConstants.TRANSPORT_OK) {
1795 status = transport.finishBackup();
1796 }
1797
1798 // Okay, the wipe really happened. Clean up our local bookkeeping.
1799 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001800 Log.i(TAG, "Device init successful");
1801 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001802 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001803 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001804 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001805 synchronized (mQueueLock) {
1806 recordInitPendingLocked(false, transportName);
1807 }
Dan Egnor726247c2009-09-29 19:12:31 -07001808 } else {
1809 // If this didn't work, requeue this one and try again
1810 // after a suitable interval
1811 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001812 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001813 synchronized (mQueueLock) {
1814 recordInitPendingLocked(true, transportName);
1815 }
1816 // do this via another alarm to make sure of the wakelock states
1817 long delay = transport.requestBackupTime();
1818 if (DEBUG) Log.w(TAG, "init failed on "
1819 + transportName + " resched in " + delay);
1820 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1821 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001822 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001823 }
1824 } catch (RemoteException e) {
1825 // can't happen; the transports are local
1826 } catch (Exception e) {
1827 Log.e(TAG, "Unexpected error performing init", e);
1828 } finally {
1829 // Done; indicate that we're finished and release the wakelock
1830 synchronized (mQueueLock) {
1831 mInitInProgress = false;
1832 }
1833 mWakelock.release();
1834 }
1835 }
1836 }
1837
Christopher Tatedf01dea2009-06-09 20:45:02 -07001838
Christopher Tate487529a2009-04-29 14:03:25 -07001839 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001840
Dan Egnor852f8e42009-09-30 11:20:45 -07001841 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001842 // Record that we need a backup pass for the caller. Since multiple callers
1843 // may share a uid, we need to note all candidates within that uid and schedule
1844 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001845 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001846
Christopher Tate63d27002009-06-16 17:16:42 -07001847 // If the caller does not hold the BACKUP permission, it can only request a
1848 // backup of its own data.
1849 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001850 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001851 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1852 targets = mBackupParticipants.get(Binder.getCallingUid());
1853 } else {
1854 // a caller with full permission can ask to back up any participating app
1855 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001856 targets = new HashSet<ApplicationInfo>();
1857 int N = mBackupParticipants.size();
1858 for (int i = 0; i < N; i++) {
1859 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1860 if (s != null) {
1861 targets.addAll(s);
1862 }
1863 }
1864 }
Christopher Tate487529a2009-04-29 14:03:25 -07001865 if (targets != null) {
1866 synchronized (mQueueLock) {
1867 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001868 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001869 // validate the caller-supplied package name against the known set of
1870 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001871 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001872 // Add the caller to the set of pending backups. If there is
1873 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001874 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001875 if (mPendingBackups.put(app, req) == null) {
1876 // Journal this request in case of crash. The put()
1877 // operation returned null when this package was not already
1878 // in the set; we want to avoid touching the disk redundantly.
1879 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001880
Christopher Tate22b60d82009-07-07 16:36:02 -07001881 if (DEBUG) {
1882 int numKeys = mPendingBackups.size();
1883 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1884 for (BackupRequest b : mPendingBackups.values()) {
1885 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1886 }
1887 }
1888 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001889 }
1890 }
Christopher Tate487529a2009-04-29 14:03:25 -07001891 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001892 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001893 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1894 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001895 }
1896 }
Christopher Tate46758122009-05-06 11:22:00 -07001897
Christopher Tatecde87f42009-06-12 12:55:53 -07001898 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001899 RandomAccessFile out = null;
1900 try {
1901 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1902 out = new RandomAccessFile(mJournal, "rws");
1903 out.seek(out.length());
1904 out.writeUTF(str);
1905 } catch (IOException e) {
1906 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1907 mJournal = null;
1908 } finally {
1909 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001910 }
1911 }
1912
Christopher Tateee0e78a2009-07-02 11:17:03 -07001913 // Clear the given package's backup data from the current transport
1914 public void clearBackupData(String packageName) {
1915 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1916 PackageInfo info;
1917 try {
1918 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1919 } catch (NameNotFoundException e) {
1920 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1921 return;
1922 }
1923
1924 // If the caller does not hold the BACKUP permission, it can only request a
1925 // wipe of its own backed-up data.
1926 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001927 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001928 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1929 apps = mBackupParticipants.get(Binder.getCallingUid());
1930 } else {
1931 // a caller with full permission can ask to back up any participating app
1932 // !!! TODO: allow data-clear of ANY app?
1933 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1934 apps = new HashSet<ApplicationInfo>();
1935 int N = mBackupParticipants.size();
1936 for (int i = 0; i < N; i++) {
1937 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1938 if (s != null) {
1939 apps.addAll(s);
1940 }
1941 }
1942 }
1943
1944 // now find the given package in the set of candidate apps
1945 for (ApplicationInfo app : apps) {
1946 if (app.packageName.equals(packageName)) {
1947 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1948 // found it; fire off the clear request
1949 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001950 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001951 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001952 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1953 new ClearParams(getTransport(mCurrentTransport), info));
1954 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001955 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001956 }
1957 break;
1958 }
1959 }
1960 }
1961
Christopher Tateace7f092009-06-15 18:07:25 -07001962 // Run a backup pass immediately for any applications that have declared
1963 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07001964 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04001965 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001966
Christopher Tateace7f092009-06-15 18:07:25 -07001967 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001968 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001969 // Because the alarms we are using can jitter, and we want an *immediate*
1970 // backup pass to happen, we restart the timer beginning with "next time,"
1971 // then manually fire the backup trigger intent ourselves.
1972 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001973 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001974 mRunBackupIntent.send();
1975 } catch (PendingIntent.CanceledException e) {
1976 // should never happen
1977 Log.e(TAG, "run-backup intent cancelled!");
1978 }
Christopher Tate46758122009-05-06 11:22:00 -07001979 }
1980 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001981
Christopher Tate8031a3d2009-07-06 16:36:05 -07001982 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001983 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001984 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1985 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001986
Christopher Tate4cc86e12009-09-21 19:36:51 -07001987 Log.i(TAG, "Backup enabled => " + enable);
1988
Christopher Tate6ef58a12009-06-29 14:56:28 -07001989 boolean wasEnabled = mEnabled;
1990 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001991 Settings.Secure.putInt(mContext.getContentResolver(),
1992 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001993 mEnabled = enable;
1994 }
1995
Christopher Tate49401dd2009-07-01 12:34:29 -07001996 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001997 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001998 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001999 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002000 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002001 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07002002 if (DEBUG) Log.i(TAG, "Opting out of backup");
2003
Christopher Tateb6787f22009-07-02 17:40:45 -07002004 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002005
2006 // This also constitutes an opt-out, so we wipe any data for
2007 // this device from the backend. We start that process with
2008 // an alarm in order to guarantee wakelock states.
2009 if (wasEnabled && mProvisioned) {
2010 // NOTE: we currently flush every registered transport, not just
2011 // the currently-active one.
2012 HashSet<String> allTransports;
2013 synchronized (mTransports) {
2014 allTransports = new HashSet<String>(mTransports.keySet());
2015 }
2016 // build the set of transports for which we are posting an init
2017 for (String transport : allTransports) {
2018 recordInitPendingLocked(true, transport);
2019 }
2020 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2021 mRunInitIntent);
2022 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002023 }
2024 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002025 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002026
Christopher Tate8031a3d2009-07-06 16:36:05 -07002027 // Mark the backup service as having been provisioned
2028 public void setBackupProvisioned(boolean available) {
2029 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2030 "setBackupProvisioned");
2031
2032 boolean wasProvisioned = mProvisioned;
2033 synchronized (this) {
2034 Settings.Secure.putInt(mContext.getContentResolver(),
2035 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2036 mProvisioned = available;
2037 }
2038
2039 synchronized (mQueueLock) {
2040 if (available && !wasProvisioned && mEnabled) {
2041 // we're now good to go, so start the backup alarms
2042 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2043 } else if (!available) {
2044 // No longer enabled, so stop running backups
2045 Log.w(TAG, "Backup service no longer provisioned");
2046 mAlarmManager.cancel(mRunBackupIntent);
2047 }
2048 }
2049 }
2050
2051 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002052 // We used to use setInexactRepeating(), but that may be linked to
2053 // backups running at :00 more often than not, creating load spikes.
2054 // Schedule at an exact time for now, and also add a bit of "fuzz".
2055
2056 Random random = new Random();
2057 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2058 random.nextInt(FUZZ_MILLIS);
2059 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2060 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002061 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002062 }
2063
Christopher Tate6ef58a12009-06-29 14:56:28 -07002064 // Report whether the backup mechanism is currently enabled
2065 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002066 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002067 return mEnabled; // no need to synchronize just to read it
2068 }
2069
Christopher Tate91717492009-06-26 21:07:13 -07002070 // Report the name of the currently active transport
2071 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002073 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002074 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002075 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002076 }
2077
Christopher Tate91717492009-06-26 21:07:13 -07002078 // Report all known, available backup transports
2079 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002080 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002081
Christopher Tate91717492009-06-26 21:07:13 -07002082 String[] list = null;
2083 ArrayList<String> known = new ArrayList<String>();
2084 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2085 if (entry.getValue() != null) {
2086 known.add(entry.getKey());
2087 }
2088 }
2089
2090 if (known.size() > 0) {
2091 list = new String[known.size()];
2092 known.toArray(list);
2093 }
2094 return list;
2095 }
2096
2097 // Select which transport to use for the next backup operation. If the given
2098 // name is not one of the available transports, no action is taken and the method
2099 // returns null.
2100 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002101 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002102
2103 synchronized (mTransports) {
2104 String prevTransport = null;
2105 if (mTransports.get(transport) != null) {
2106 prevTransport = mCurrentTransport;
2107 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002108 Settings.Secure.putString(mContext.getContentResolver(),
2109 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002110 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2111 + " returning " + prevTransport);
2112 } else {
2113 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2114 }
2115 return prevTransport;
2116 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002117 }
2118
2119 // Callback: a requested backup agent has been instantiated. This should only
2120 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002121 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002122 synchronized(mAgentConnectLock) {
2123 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2124 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2125 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2126 mConnectedAgent = agent;
2127 mConnecting = false;
2128 } else {
2129 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2130 + " claiming agent connected");
2131 }
2132 mAgentConnectLock.notifyAll();
2133 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002134 }
2135
2136 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2137 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002138 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002139 public void agentDisconnected(String packageName) {
2140 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002141 synchronized(mAgentConnectLock) {
2142 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2143 mConnectedAgent = null;
2144 mConnecting = false;
2145 } else {
2146 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2147 + " claiming agent disconnected");
2148 }
2149 mAgentConnectLock.notifyAll();
2150 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002151 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002152
Christopher Tate8c850b72009-06-07 19:33:20 -07002153 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002154 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002155 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002156
2157 synchronized(this) {
2158 if (mActiveRestoreSession != null) {
2159 Log.d(TAG, "Restore session requested but one already active");
2160 return null;
2161 }
Christopher Tate80202c82010-01-25 19:37:47 -08002162 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002163 }
2164 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002165 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002166
Christopher Tate44a27902010-01-27 17:15:49 -08002167 // Note that a currently-active backup agent has notified us that it has
2168 // completed the given outstanding asynchronous backup/restore operation.
2169 public void opComplete(int token) {
2170 synchronized (mCurrentOpLock) {
2171 if (DEBUG) Log.v(TAG, "opComplete: " + token);
2172 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2173 mCurrentOpLock.notifyAll();
2174 }
2175 }
2176
Christopher Tate9b3905c2009-06-08 15:24:01 -07002177 // ----- Restore session -----
2178
Christopher Tate80202c82010-01-25 19:37:47 -08002179 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002180 private static final String TAG = "RestoreSession";
2181
Christopher Tate9b3905c2009-06-08 15:24:01 -07002182 private IBackupTransport mRestoreTransport = null;
2183 RestoreSet[] mRestoreSets = null;
2184
Christopher Tate80202c82010-01-25 19:37:47 -08002185 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002186 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002187 }
2188
2189 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002190 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002191 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002192 "getAvailableRestoreSets");
2193
Christopher Tatef68eb502009-06-16 11:02:01 -07002194 try {
Christopher Tate43383042009-07-13 15:17:13 -07002195 if (mRestoreTransport == null) {
2196 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002197 return null;
2198 }
2199 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002200 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002201 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002202 }
2203 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002204 } catch (Exception e) {
2205 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2206 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002207 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002208 }
2209
Dan Egnor0084da52009-07-29 12:57:16 -07002210 public synchronized int performRestore(long token, IRestoreObserver observer) {
2211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2212 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002213
Christopher Tatef2c321a2009-08-10 15:43:36 -07002214 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2215 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002216
Dan Egnor0084da52009-07-29 12:57:16 -07002217 if (mRestoreTransport == null || mRestoreSets == null) {
2218 Log.e(TAG, "Ignoring performRestore() with no restore set");
2219 return -1;
2220 }
2221
Christopher Tate21ab6a52009-09-24 18:01:46 -07002222 synchronized (mQueueLock) {
2223 if (mBackupOrRestoreInProgress) {
2224 Log.e(TAG, "Backup pass in progress, restore aborted");
2225 return -1;
2226 }
2227
2228 for (int i = 0; i < mRestoreSets.length; i++) {
2229 if (token == mRestoreSets[i].token) {
2230 long oldId = Binder.clearCallingIdentity();
2231 // Suppress backups until the restore operation is finished
2232 mBackupOrRestoreInProgress = true;
2233 mWakelock.acquire();
2234 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2235 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2236 mBackupHandler.sendMessage(msg);
2237 Binder.restoreCallingIdentity(oldId);
2238 return 0;
2239 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002240 }
2241 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002242
2243 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002244 return -1;
2245 }
2246
Dan Egnor0084da52009-07-29 12:57:16 -07002247 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002248 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002249 "endRestoreSession");
2250
Dan Egnor0084da52009-07-29 12:57:16 -07002251 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002252
Dan Egnor0084da52009-07-29 12:57:16 -07002253 synchronized (this) {
2254 try {
2255 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2256 } catch (Exception e) {
2257 Log.e(TAG, "Error in finishRestore", e);
2258 } finally {
2259 mRestoreTransport = null;
2260 }
2261 }
2262
2263 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002264 if (BackupManagerService.this.mActiveRestoreSession == this) {
2265 BackupManagerService.this.mActiveRestoreSession = null;
2266 } else {
2267 Log.e(TAG, "ending non-current restore session");
2268 }
2269 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002270 }
2271 }
2272
Christopher Tate043dadc2009-06-02 16:11:00 -07002273
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002274 @Override
2275 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2276 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002277 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002278 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
2279 + (!mBackupOrRestoreInProgress ? "not " : "") + "in progress / "
2280 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init / "
2281 + (!mInitInProgress ? "not " : "") + "initializing");
2282 pw.println("Last backup pass: " + mLastBackupPass
2283 + " (now = " + System.currentTimeMillis() + ')');
2284 pw.println(" next scheduled: " + mNextBackupPass);
2285
Christopher Tate91717492009-06-26 21:07:13 -07002286 pw.println("Available transports:");
2287 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002288 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2289 try {
2290 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2291 for (File f : dir.listFiles()) {
2292 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2293 }
2294 } catch (RemoteException e) {
2295 Log.e(TAG, "Error in transportDirName()", e);
2296 pw.println(" Error: " + e);
2297 }
Christopher Tate91717492009-06-26 21:07:13 -07002298 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002299
2300 pw.println("Pending init: " + mPendingInits.size());
2301 for (String s : mPendingInits) {
2302 pw.println(" " + s);
2303 }
2304
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002305 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002306 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002307 for (int i=0; i<N; i++) {
2308 int uid = mBackupParticipants.keyAt(i);
2309 pw.print(" uid: ");
2310 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002311 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2312 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002313 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002314 }
2315 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002316
Christopher Tate73e02522009-07-15 14:18:26 -07002317 pw.println("Ever backed up: " + mEverStoredApps.size());
2318 for (String pkg : mEverStoredApps) {
2319 pw.println(" " + pkg);
2320 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002321
2322 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002323 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002324 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002325 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002326 }
2327 }
Christopher Tate487529a2009-04-29 14:03:25 -07002328}