blob: ef184d2aa4eb5ce66f5f294dda2cb5ac6c32adcd [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 Tate55f931a2009-09-29 17:17:34 -0700160 volatile long mLastBackupPass;
161 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700162
Christopher Tate55f931a2009-09-29 17:17:34 -0700163 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700164 final Object mClearDataLock = new Object();
165 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700166
Christopher Tate91717492009-06-26 21:07:13 -0700167 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700168 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700169 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700170 String mCurrentTransport;
171 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800172 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700173
Christopher Tate73e02522009-07-15 14:18:26 -0700174 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700175 public IBackupTransport transport;
176 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700177 public long token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700178
Dan Egnor156411d2009-06-26 13:20:02 -0700179 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700180 transport = _transport;
181 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700182 token = _token;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700183 }
184 }
185
Christopher Tate73e02522009-07-15 14:18:26 -0700186 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700187 public IBackupTransport transport;
188 public PackageInfo packageInfo;
189
190 ClearParams(IBackupTransport _transport, PackageInfo _info) {
191 transport = _transport;
192 packageInfo = _info;
193 }
194 }
195
Christopher Tate44a27902010-01-27 17:15:49 -0800196 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
197 // token is the index of the entry in the pending-operations list.
198 static final int OP_PENDING = 0;
199 static final int OP_ACKNOWLEDGED = 1;
200 static final int OP_TIMEOUT = -1;
201
202 final SparseIntArray mCurrentOperations = new SparseIntArray();
203 final Object mCurrentOpLock = new Object();
204 final Random mTokenGenerator = new Random();
205
Christopher Tate5cb400b2009-06-25 16:03:14 -0700206 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700207 File mBaseStateDir;
208 File mDataDir;
209 File mJournalDir;
210 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700211
212 // Keep a log of all the apps we've ever backed up
213 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700214 HashSet<String> mEverStoredApps = new HashSet<String>();
215
Christopher Tate4cc86e12009-09-21 19:36:51 -0700216 // Persistently track the need to do a full init
217 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
218 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700219
Christopher Tate44a27902010-01-27 17:15:49 -0800220 // ----- Asynchronous backup/restore handler thread -----
221
222 private class BackupHandler extends Handler {
223 public BackupHandler(Looper looper) {
224 super(looper);
225 }
226
227 public void handleMessage(Message msg) {
228
229 switch (msg.what) {
230 case MSG_RUN_BACKUP:
231 {
232 mLastBackupPass = System.currentTimeMillis();
233 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
234
235 IBackupTransport transport = getTransport(mCurrentTransport);
236 if (transport == null) {
237 Log.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800238 mWakelock.release();
239 break;
240 }
241
242 // snapshot the pending-backup set and work on that
243 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
244 synchronized (mQueueLock) {
245 // Do we have any work to do?
246 if (mPendingBackups.size() > 0) {
247 for (BackupRequest b: mPendingBackups.values()) {
248 queue.add(b);
249 }
250 if (DEBUG) Log.v(TAG, "clearing pending backups");
251 mPendingBackups.clear();
252
253 // Start a new backup-queue journal file too
254 File oldJournal = mJournal;
255 mJournal = null;
256
257 // At this point, we have started a new journal file, and the old
258 // file identity is being passed to the backup processing thread.
259 // When it completes successfully, that old journal file will be
260 // deleted. If we crash prior to that, the old journal is parsed
261 // at next boot and the journaled requests fulfilled.
262 (new PerformBackupTask(transport, queue, oldJournal)).run();
263 } else {
264 Log.v(TAG, "Backup requested but nothing pending");
Christopher Tate44a27902010-01-27 17:15:49 -0800265 mWakelock.release();
266 }
267 }
268 break;
269 }
270
271 case MSG_RUN_FULL_BACKUP:
272 break;
273
274 case MSG_RUN_RESTORE:
275 {
276 RestoreParams params = (RestoreParams)msg.obj;
277 Log.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
278 (new PerformRestoreTask(params.transport, params.observer,
279 params.token)).run();
280 break;
281 }
282
283 case MSG_RUN_CLEAR:
284 {
285 ClearParams params = (ClearParams)msg.obj;
286 (new PerformClearTask(params.transport, params.packageInfo)).run();
287 break;
288 }
289
290 case MSG_RUN_INITIALIZE:
291 {
292 HashSet<String> queue;
293
294 // Snapshot the pending-init queue and work on that
295 synchronized (mQueueLock) {
296 queue = new HashSet<String>(mPendingInits);
297 mPendingInits.clear();
298 }
299
300 (new PerformInitializeTask(queue)).run();
301 break;
302 }
303
304 case MSG_TIMEOUT:
305 {
306 synchronized (mCurrentOpLock) {
307 final int token = msg.arg1;
308 int state = mCurrentOperations.get(token, OP_TIMEOUT);
309 if (state == OP_PENDING) {
310 if (DEBUG) Log.v(TAG, "TIMEOUT: token=" + token);
311 mCurrentOperations.put(token, OP_TIMEOUT);
312 }
313 mCurrentOpLock.notifyAll();
314 }
315 break;
316 }
317 }
318 }
319 }
320
321 // ----- Main service implementation -----
322
Christopher Tate487529a2009-04-29 14:03:25 -0700323 public BackupManagerService(Context context) {
324 mContext = context;
325 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700326 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700327
Christopher Tateb6787f22009-07-02 17:40:45 -0700328 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
329 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
330
Christopher Tate44a27902010-01-27 17:15:49 -0800331 mBackupManagerBinder = asInterface(asBinder());
332
333 // spin up the backup/restore handler thread
334 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
335 mHandlerThread.start();
336 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
337
Christopher Tate22b87872009-05-04 16:41:53 -0700338 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700339 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700340 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700341 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700342 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800343 // If Encrypted file systems is enabled or disabled, this call will return the
344 // correct directory.
345 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
346 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700347 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700348
Christopher Tate4cc86e12009-09-21 19:36:51 -0700349 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700350 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700351 IntentFilter filter = new IntentFilter();
352 filter.addAction(RUN_BACKUP_ACTION);
353 context.registerReceiver(mRunBackupReceiver, filter,
354 android.Manifest.permission.BACKUP, null);
355
356 mRunInitReceiver = new RunInitializeReceiver();
357 filter = new IntentFilter();
358 filter.addAction(RUN_INITIALIZE_ACTION);
359 context.registerReceiver(mRunInitReceiver, filter,
360 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700361
362 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700363 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
364 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
365
Christopher Tate4cc86e12009-09-21 19:36:51 -0700366 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
367 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
368 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
369
Christopher Tatecde87f42009-06-12 12:55:53 -0700370 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700371 mJournalDir = new File(mBaseStateDir, "pending");
372 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700373 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700374
Christopher Tate73e02522009-07-15 14:18:26 -0700375 // Set up the various sorts of package tracking we do
376 initPackageTracking();
377
Christopher Tateabce4e82009-06-18 18:35:32 -0700378 // Build our mapping of uid to backup client services. This implicitly
379 // schedules a backup pass on the Package Manager metadata the first
380 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700381 synchronized (mBackupParticipants) {
382 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700383 }
384
Dan Egnor87a02bc2009-06-17 02:30:10 -0700385 // Set up our transport options and initialize the default transport
386 // TODO: Have transports register themselves somehow?
387 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700388 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700389 ComponentName localName = new ComponentName(context, LocalTransport.class);
390 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700391
Christopher Tate91717492009-06-26 21:07:13 -0700392 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700393 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
394 Settings.Secure.BACKUP_TRANSPORT);
395 if ("".equals(mCurrentTransport)) {
396 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700397 }
Christopher Tate91717492009-06-26 21:07:13 -0700398 if (DEBUG) Log.v(TAG, "Starting with transport " + mCurrentTransport);
399
400 // Attach to the Google backup transport. When this comes up, it will set
401 // itself as the current transport because we explicitly reset mCurrentTransport
402 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700403 Intent intent = new Intent().setComponent(new ComponentName(
404 "com.google.android.backup",
405 "com.google.android.backup.BackupTransportService"));
406 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700407
Christopher Tatecde87f42009-06-12 12:55:53 -0700408 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700409 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700410 parseLeftoverJournals();
411
Christopher Tateb6787f22009-07-02 17:40:45 -0700412 // Power management
413 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
414
415 // Start the backup passes going
416 setBackupEnabled(areEnabled);
417 }
418
419 private class RunBackupReceiver extends BroadcastReceiver {
420 public void onReceive(Context context, Intent intent) {
421 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700422 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700423 if (mPendingInits.size() > 0) {
424 // If there are pending init operations, we process those
425 // and then settle into the usual periodic backup schedule.
426 if (DEBUG) Log.v(TAG, "Init pending at scheduled backup");
427 try {
428 mAlarmManager.cancel(mRunInitIntent);
429 mRunInitIntent.send();
430 } catch (PendingIntent.CanceledException ce) {
431 Log.e(TAG, "Run init intent cancelled");
432 // can't really do more than bail here
433 }
434 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800435 // Don't run backups now if we're disabled or not yet
436 // fully set up.
437 if (mEnabled && mProvisioned) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700438 if (DEBUG) Log.v(TAG, "Running a backup pass");
439
440 // Acquire the wakelock and pass it to the backup thread. it will
441 // be released once backup concludes.
442 mWakelock.acquire();
443
444 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
445 mBackupHandler.sendMessage(msg);
446 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800447 Log.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700448 }
449 }
450 }
451 }
452 }
453 }
454
455 private class RunInitializeReceiver extends BroadcastReceiver {
456 public void onReceive(Context context, Intent intent) {
457 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
458 synchronized (mQueueLock) {
459 if (DEBUG) Log.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700460
461 // Acquire the wakelock and pass it to the init thread. it will
462 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700463 mWakelock.acquire();
464
Christopher Tate4cc86e12009-09-21 19:36:51 -0700465 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700466 mBackupHandler.sendMessage(msg);
467 }
468 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700469 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700470 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700471
Christopher Tate73e02522009-07-15 14:18:26 -0700472 private void initPackageTracking() {
473 if (DEBUG) Log.v(TAG, "Initializing package tracking");
474
Christopher Tatee97e8072009-07-15 16:45:50 -0700475 // Keep a log of what apps we've ever backed up. Because we might have
476 // rebooted in the middle of an operation that was removing something from
477 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700478 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700479 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700480
Christopher Tatee97e8072009-07-15 16:45:50 -0700481 // If we were in the middle of removing something from the ever-backed-up
482 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700483 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700484 if (tempProcessedFile.exists()) {
485 tempProcessedFile.delete();
486 }
487
Dan Egnor852f8e42009-09-30 11:20:45 -0700488 // If there are previous contents, parse them out then start a new
489 // file to continue the recordkeeping.
490 if (mEverStored.exists()) {
491 RandomAccessFile temp = null;
492 RandomAccessFile in = null;
493
494 try {
495 temp = new RandomAccessFile(tempProcessedFile, "rws");
496 in = new RandomAccessFile(mEverStored, "r");
497
498 while (true) {
499 PackageInfo info;
500 String pkg = in.readUTF();
501 try {
502 info = mPackageManager.getPackageInfo(pkg, 0);
503 mEverStoredApps.add(pkg);
504 temp.writeUTF(pkg);
505 if (DEBUG) Log.v(TAG, " + " + pkg);
506 } catch (NameNotFoundException e) {
507 // nope, this package was uninstalled; don't include it
508 if (DEBUG) Log.v(TAG, " - " + pkg);
509 }
510 }
511 } catch (EOFException e) {
512 // Once we've rewritten the backup history log, atomically replace the
513 // old one with the new one then reopen the file for continuing use.
514 if (!tempProcessedFile.renameTo(mEverStored)) {
515 Log.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
516 }
517 } catch (IOException e) {
518 Log.e(TAG, "Error in processed file", e);
519 } finally {
520 try { if (temp != null) temp.close(); } catch (IOException e) {}
521 try { if (in != null) in.close(); } catch (IOException e) {}
522 }
523 }
524
Christopher Tate73e02522009-07-15 14:18:26 -0700525 // Register for broadcasts about package install, etc., so we can
526 // update the provider list.
527 IntentFilter filter = new IntentFilter();
528 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
529 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
530 filter.addDataScheme("package");
531 mContext.registerReceiver(mBroadcastReceiver, filter);
532 }
533
Christopher Tatecde87f42009-06-12 12:55:53 -0700534 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700535 for (File f : mJournalDir.listFiles()) {
536 if (mJournal == null || f.compareTo(mJournal) != 0) {
537 // This isn't the current journal, so it must be a leftover. Read
538 // out the package names mentioned there and schedule them for
539 // backup.
540 RandomAccessFile in = null;
541 try {
542 Log.i(TAG, "Found stale backup journal, scheduling:");
543 in = new RandomAccessFile(f, "r");
544 while (true) {
545 String packageName = in.readUTF();
546 Log.i(TAG, " + " + packageName);
547 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700548 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700549 } catch (EOFException e) {
550 // no more data; we're done
551 } catch (Exception e) {
552 Log.e(TAG, "Can't read " + f, e);
553 } finally {
554 // close/delete the file
555 try { if (in != null) in.close(); } catch (IOException e) {}
556 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700557 }
558 }
559 }
560 }
561
Christopher Tate4cc86e12009-09-21 19:36:51 -0700562 // Maintain persistent state around whether need to do an initialize operation.
563 // Must be called with the queue lock held.
564 void recordInitPendingLocked(boolean isPending, String transportName) {
565 if (DEBUG) Log.i(TAG, "recordInitPendingLocked: " + isPending
566 + " on transport " + transportName);
567 try {
568 IBackupTransport transport = getTransport(transportName);
569 String transportDirName = transport.transportDirName();
570 File stateDir = new File(mBaseStateDir, transportDirName);
571 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
572
573 if (isPending) {
574 // We need an init before we can proceed with sending backup data.
575 // Record that with an entry in our set of pending inits, as well as
576 // journaling it via creation of a sentinel file.
577 mPendingInits.add(transportName);
578 try {
579 (new FileOutputStream(initPendingFile)).close();
580 } catch (IOException ioe) {
581 // Something is badly wrong with our permissions; just try to move on
582 }
583 } else {
584 // No more initialization needed; wipe the journal and reset our state.
585 initPendingFile.delete();
586 mPendingInits.remove(transportName);
587 }
588 } catch (RemoteException e) {
589 // can't happen; the transport is local
590 }
591 }
592
Christopher Tated55e18a2009-09-21 10:12:59 -0700593 // Reset all of our bookkeeping, in response to having been told that
594 // the backend data has been wiped [due to idle expiry, for example],
595 // so we must re-upload all saved settings.
596 void resetBackupState(File stateFileDir) {
597 synchronized (mQueueLock) {
598 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700599 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700600 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700601
602 // Remove all the state files
603 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700604 // ... but don't touch the needs-init sentinel
605 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
606 sf.delete();
607 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700608 }
609
610 // Enqueue a new backup of every participant
611 int N = mBackupParticipants.size();
612 for (int i=0; i<N; i++) {
613 int uid = mBackupParticipants.keyAt(i);
614 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
615 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700616 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700617 }
618 }
619 }
620 }
621
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800622 // Add a transport to our set of available backends. If 'transport' is null, this
623 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700624 private void registerTransport(String name, IBackupTransport transport) {
625 synchronized (mTransports) {
Christopher Tate34ebd0e2009-07-06 15:44:54 -0700626 if (DEBUG) Log.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800627 if (transport != null) {
628 mTransports.put(name, transport);
629 } else {
630 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800631 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800632 mCurrentTransport = null;
633 }
634 // Nothing further to do in the unregistration case
635 return;
636 }
Christopher Tate91717492009-06-26 21:07:13 -0700637 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700638
639 // If the init sentinel file exists, we need to be sure to perform the init
640 // as soon as practical. We also create the state directory at registration
641 // time to ensure it's present from the outset.
642 try {
643 String transportName = transport.transportDirName();
644 File stateDir = new File(mBaseStateDir, transportName);
645 stateDir.mkdirs();
646
647 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
648 if (initSentinel.exists()) {
649 synchronized (mQueueLock) {
650 mPendingInits.add(transportName);
651
652 // TODO: pick a better starting time than now + 1 minute
653 long delay = 1000 * 60; // one minute, in milliseconds
654 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
655 System.currentTimeMillis() + delay, mRunInitIntent);
656 }
657 }
658 } catch (RemoteException e) {
659 // can't happen, the transport is local
660 }
Christopher Tate91717492009-06-26 21:07:13 -0700661 }
662
Christopher Tate3799bc22009-05-06 16:13:56 -0700663 // ----- Track installation/removal of packages -----
664 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
665 public void onReceive(Context context, Intent intent) {
666 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
667
668 Uri uri = intent.getData();
669 if (uri == null) {
670 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700671 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700672 String pkgName = uri.getSchemeSpecificPart();
673 if (pkgName == null) {
674 return;
675 }
676
677 String action = intent.getAction();
678 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
679 synchronized (mBackupParticipants) {
680 Bundle extras = intent.getExtras();
681 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
682 // The package was just upgraded
683 updatePackageParticipantsLocked(pkgName);
684 } else {
685 // The package was just added
686 addPackageParticipantsLocked(pkgName);
687 }
688 }
689 }
690 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
691 Bundle extras = intent.getExtras();
692 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
693 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
694 } else {
695 synchronized (mBackupParticipants) {
696 removePackageParticipantsLocked(pkgName);
697 }
698 }
699 }
700 }
701 };
702
Dan Egnor87a02bc2009-06-17 02:30:10 -0700703 // ----- Track connection to GoogleBackupTransport service -----
704 ServiceConnection mGoogleConnection = new ServiceConnection() {
705 public void onServiceConnected(ComponentName name, IBinder service) {
706 if (DEBUG) Log.v(TAG, "Connected to Google transport");
707 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700708 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700709 }
710
711 public void onServiceDisconnected(ComponentName name) {
712 if (DEBUG) Log.v(TAG, "Disconnected from Google transport");
713 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700714 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700715 }
716 };
717
Christopher Tate181fafa2009-05-14 11:12:14 -0700718 // Add the backup agents in the given package to our set of known backup participants.
719 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700720 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700721 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700722 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700723 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700724 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700725 }
726
Christopher Tate181fafa2009-05-14 11:12:14 -0700727 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700728 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700729 if (DEBUG) {
Dan Egnorefe52642009-06-24 00:16:33 -0700730 Log.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
731 for (PackageInfo p : targetPkgs) {
Christopher Tate111bd4a2009-06-24 17:29:38 -0700732 Log.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700733 + " uid=" + p.applicationInfo.uid
734 + " killAfterRestore="
735 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
736 + " restoreNeedsApplication="
737 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0) ? "true" : "false")
738 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700739 }
740 }
741
Dan Egnorefe52642009-06-24 00:16:33 -0700742 for (PackageInfo pkg : targetPkgs) {
743 if (packageName == null || pkg.packageName.equals(packageName)) {
744 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700745 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700746 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700747 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700748 mBackupParticipants.put(uid, set);
749 }
Dan Egnorefe52642009-06-24 00:16:33 -0700750 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700751
752 // If we've never seen this app before, schedule a backup for it
753 if (!mEverStoredApps.contains(pkg.packageName)) {
754 if (DEBUG) Log.i(TAG, "New app " + pkg.packageName
755 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700756 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700757 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700758 }
Christopher Tate487529a2009-04-29 14:03:25 -0700759 }
760 }
761
Christopher Tate6785dd82009-06-18 15:58:25 -0700762 // Remove the given package's entry from our known active set. If
763 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700764 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700765 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700766 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700767 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700768 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700769 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700770 int flags = PackageManager.GET_SIGNATURES;
771 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700772 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700773 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700774 }
775 } else {
776 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700777 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700778 }
779 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700780 }
781
Joe Onorato8ad02812009-05-13 01:41:44 -0400782 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700783 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700784 if (DEBUG) {
785 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
786 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700787 for (PackageInfo p : agents) {
788 Log.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700789 }
790 }
Dan Egnorefe52642009-06-24 00:16:33 -0700791 for (PackageInfo pkg : agents) {
792 if (packageName == null || pkg.packageName.equals(packageName)) {
793 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700794 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700795 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700796 // Find the existing entry with the same package name, and remove it.
797 // We can't just remove(app) because the instances are different.
798 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700799 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700800 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700801 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700802 break;
803 }
804 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700805 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700806 mBackupParticipants.delete(uid);
807 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700808 }
809 }
810 }
811 }
812
Christopher Tate181fafa2009-05-14 11:12:14 -0700813 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700814 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700815 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700816 int flags = PackageManager.GET_SIGNATURES;
817 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
818 int N = packages.size();
819 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700820 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700821 try {
822 ApplicationInfo app = pkg.applicationInfo;
823 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
824 || app.backupAgentName == null
825 || (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
826 pkg.packageName) != PackageManager.PERMISSION_GRANTED)) {
827 packages.remove(a);
828 }
829 else {
830 // we will need the shared library path, so look that up and store it here
831 app = mPackageManager.getApplicationInfo(pkg.packageName,
832 PackageManager.GET_SHARED_LIBRARY_FILES);
833 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
834 }
835 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700836 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700837 }
838 }
Dan Egnorefe52642009-06-24 00:16:33 -0700839 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700840 }
Christopher Tateaa088442009-06-16 18:25:46 -0700841
Christopher Tate3799bc22009-05-06 16:13:56 -0700842 // Reset the given package's known backup participants. Unlike add/remove, the update
843 // action cannot be passed a null package name.
844 void updatePackageParticipantsLocked(String packageName) {
845 if (packageName == null) {
846 Log.e(TAG, "updatePackageParticipants called with null package name");
847 return;
848 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700849 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700850
851 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700852 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700853 removePackageParticipantsLockedInner(packageName, allApps);
854 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700855 }
856
Christopher Tate73e02522009-07-15 14:18:26 -0700857 // Called from the backup thread: record that the given app has been successfully
858 // backed up at least once
859 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700860 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
861
862 synchronized (mEverStoredApps) {
863 if (!mEverStoredApps.add(packageName)) return;
864
865 RandomAccessFile out = null;
866 try {
867 out = new RandomAccessFile(mEverStored, "rws");
868 out.seek(out.length());
869 out.writeUTF(packageName);
870 } catch (IOException e) {
871 Log.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
872 } finally {
873 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -0700874 }
875 }
876 }
877
Christopher Tatee97e8072009-07-15 16:45:50 -0700878 // Remove our awareness of having ever backed up the given package
879 void removeEverBackedUp(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700880 if (DEBUG) Log.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -0700881
Dan Egnor852f8e42009-09-30 11:20:45 -0700882 synchronized (mEverStoredApps) {
883 // Rewrite the file and rename to overwrite. If we reboot in the middle,
884 // we'll recognize on initialization time that the package no longer
885 // exists and fix it up then.
886 File tempKnownFile = new File(mBaseStateDir, "processed.new");
887 RandomAccessFile known = null;
888 try {
889 known = new RandomAccessFile(tempKnownFile, "rws");
890 mEverStoredApps.remove(packageName);
891 for (String s : mEverStoredApps) {
892 known.writeUTF(s);
893 if (DEBUG) Log.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -0700894 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700895 known.close();
896 known = null;
897 if (!tempKnownFile.renameTo(mEverStored)) {
898 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
899 }
900 } catch (IOException e) {
901 // Bad: we couldn't create the new copy. For safety's sake we
902 // abandon the whole process and remove all what's-backed-up
903 // state entirely, meaning we'll force a backup pass for every
904 // participant on the next boot or [re]install.
905 Log.w(TAG, "Error rewriting " + mEverStored, e);
906 mEverStoredApps.clear();
907 tempKnownFile.delete();
908 mEverStored.delete();
909 } finally {
910 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -0700911 }
912 }
913 }
914
Dan Egnor87a02bc2009-06-17 02:30:10 -0700915 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -0700916 private IBackupTransport getTransport(String transportName) {
917 synchronized (mTransports) {
918 IBackupTransport transport = mTransports.get(transportName);
919 if (transport == null) {
920 Log.w(TAG, "Requested unavailable transport: " + transportName);
921 }
922 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -0700923 }
Christopher Tate8c850b72009-06-07 19:33:20 -0700924 }
925
Christopher Tatedf01dea2009-06-09 20:45:02 -0700926 // fire off a backup agent, blocking until it attaches or times out
927 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
928 IBackupAgent agent = null;
929 synchronized(mAgentConnectLock) {
930 mConnecting = true;
931 mConnectedAgent = null;
932 try {
933 if (mActivityManager.bindBackupAgent(app, mode)) {
934 Log.d(TAG, "awaiting agent for " + app);
935
936 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -0700937 // only wait 10 seconds for the clear data to happen
938 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
939 while (mConnecting && mConnectedAgent == null
940 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -0700941 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700942 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -0700943 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -0700944 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -0700945 return null;
946 }
947 }
948
949 // if we timed out with no connect, abort and move on
950 if (mConnecting == true) {
951 Log.w(TAG, "Timeout waiting for agent " + app);
952 return null;
953 }
954 agent = mConnectedAgent;
955 }
956 } catch (RemoteException e) {
957 // can't happen
958 }
959 }
960 return agent;
961 }
962
Christopher Tatec7b31e32009-06-10 15:49:30 -0700963 // clear an application's data, blocking until the operation completes or times out
964 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -0700965 // Don't wipe packages marked allowClearUserData=false
966 try {
967 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
968 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
969 if (DEBUG) Log.i(TAG, "allowClearUserData=false so not wiping "
970 + packageName);
971 return;
972 }
973 } catch (NameNotFoundException e) {
974 Log.w(TAG, "Tried to clear data for " + packageName + " but not found");
975 return;
976 }
977
Christopher Tatec7b31e32009-06-10 15:49:30 -0700978 ClearDataObserver observer = new ClearDataObserver();
979
980 synchronized(mClearDataLock) {
981 mClearingData = true;
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700982 /* This is causing some critical processes to be killed during setup.
983 Temporarily revert this change until we find a better solution.
Christopher Tate9dfdac52009-08-06 14:57:53 -0700984 try {
985 mActivityManager.clearApplicationUserData(packageName, observer);
986 } catch (RemoteException e) {
987 // can't happen because the activity manager is in this process
988 }
Amith Yamasani2e6bca62009-08-07 20:26:13 -0700989 */
990 mPackageManager.clearApplicationUserData(packageName, observer);
Christopher Tatec7b31e32009-06-10 15:49:30 -0700991
992 // only wait 10 seconds for the clear data to happen
993 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
994 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
995 try {
996 mClearDataLock.wait(5000);
997 } catch (InterruptedException e) {
998 // won't happen, but still.
999 mClearingData = false;
1000 }
1001 }
1002 }
1003 }
1004
1005 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001006 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001007 synchronized(mClearDataLock) {
1008 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001009 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001010 }
1011 }
1012 }
1013
Christopher Tate44a27902010-01-27 17:15:49 -08001014 // -----
1015 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1016 boolean waitUntilOperationComplete(int token) {
1017 int finalState = OP_PENDING;
1018 synchronized (mCurrentOpLock) {
1019 try {
1020 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1021 try {
1022 mCurrentOpLock.wait();
1023 } catch (InterruptedException e) {}
1024 }
1025 } catch (IndexOutOfBoundsException e) {
1026 // the operation has been mysteriously cleared from our
1027 // bookkeeping -- consider this a success and ignore it.
1028 }
1029 }
1030 mBackupHandler.removeMessages(MSG_TIMEOUT);
1031 if (DEBUG) Log.v(TAG, "operation " + token + " complete: finalState=" + finalState);
1032 return finalState == OP_ACKNOWLEDGED;
1033 }
1034
1035 void prepareOperationTimeout(int token, long interval) {
1036 if (DEBUG) Log.v(TAG, "starting timeout: token=" + token + " interval=" + interval);
1037 mCurrentOperations.put(token, OP_PENDING);
1038 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1039 mBackupHandler.sendMessageDelayed(msg, interval);
1040 }
1041
Christopher Tate043dadc2009-06-02 16:11:00 -07001042 // ----- Back up a set of applications via a worker thread -----
1043
Christopher Tate44a27902010-01-27 17:15:49 -08001044 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001045 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001046 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001047 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001048 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001049 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001050
Christopher Tate44a27902010-01-27 17:15:49 -08001051 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001052 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001053 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001054 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001055 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001056
1057 try {
1058 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1059 } catch (RemoteException e) {
1060 // can't happen; the transport is local
1061 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001062 }
1063
Christopher Tate043dadc2009-06-02 16:11:00 -07001064 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001065 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001066 long startRealtime = SystemClock.elapsedRealtime();
Christopher Tate043dadc2009-06-02 16:11:00 -07001067 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
1068
Christopher Tate79588342009-06-30 16:11:49 -07001069 // Backups run at background priority
1070 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1071
Christopher Tate043dadc2009-06-02 16:11:00 -07001072 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001073 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001074
Dan Egnor852f8e42009-09-30 11:20:45 -07001075 // If we haven't stored package manager metadata yet, we must init the transport.
1076 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1077 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
1078 Log.i(TAG, "Initializing (wiping) backup state and transport storage");
1079 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001080 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001081 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001082 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001083 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001084 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Dan Egnor726247c2009-09-29 19:12:31 -07001085 Log.e(TAG, "Transport error in initializeDevice()");
1086 }
Dan Egnor01445162009-09-21 17:04:05 -07001087 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001088
1089 // The package manager doesn't have a proper <application> etc, but since
1090 // it's running here in the system process we can just set up its agent
1091 // directly and use a synthetic BackupRequest. We always run this pass
1092 // because it's cheap and this way we guarantee that we don't get out of
1093 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001094 if (status == BackupConstants.TRANSPORT_OK) {
1095 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1096 mPackageManager, allAgentPackages());
1097 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1098 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1099 status = processOneBackup(pmRequest,
1100 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1101 }
Christopher Tate90967f42009-09-20 15:28:33 -07001102
Dan Egnor01445162009-09-21 17:04:05 -07001103 if (status == BackupConstants.TRANSPORT_OK) {
1104 // Now run all the backups in our queue
1105 status = doQueuedBackups(mTransport);
1106 }
1107
1108 if (status == BackupConstants.TRANSPORT_OK) {
1109 // Tell the transport to finish everything it has buffered
1110 status = mTransport.finishBackup();
1111 if (status == BackupConstants.TRANSPORT_OK) {
1112 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001113 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001114 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001115 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Dan Egnor01445162009-09-21 17:04:05 -07001116 Log.e(TAG, "Transport error in finishBackup()");
1117 }
1118 }
1119
Dan Egnor01445162009-09-21 17:04:05 -07001120 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001121 // The backend reports that our dataset has been wiped. We need to
1122 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001123 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001124 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001125 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001126 }
1127 } catch (Exception e) {
1128 Log.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001129 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001130 } finally {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001131 // If things went wrong, we need to re-stage the apps we had expected
1132 // to be backing up in this pass. This journals the package names in
1133 // the current active pending-backup file, not in the we are holding
1134 // here in mJournal.
1135 if (status != BackupConstants.TRANSPORT_OK) {
1136 Log.w(TAG, "Backup pass unsuccessful, restaging");
1137 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001138 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001139 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001140
1141 // We also want to reset the backup schedule based on whatever
1142 // the transport suggests by way of retry/backoff time.
1143 try {
1144 startBackupAlarmsLocked(mTransport.requestBackupTime());
1145 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001146 }
1147
1148 // Either backup was successful, in which case we of course do not need
1149 // this pass's journal any more; or it failed, in which case we just
1150 // re-enqueued all of these packages in the current active journal.
1151 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001152 if (mJournal != null && !mJournal.delete()) {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001153 Log.e(TAG, "Unable to remove backup journal file " + mJournal);
1154 }
1155
Christopher Tatec2af5d32010-02-02 15:18:58 -08001156 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001157 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001158 backupNow();
1159 }
1160
Dan Egnorbb9001c2009-07-27 12:20:13 -07001161 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001162 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001163 }
1164
Dan Egnor01445162009-09-21 17:04:05 -07001165 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001166 for (BackupRequest request : mQueue) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001167 Log.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001168
Christopher Tate0749dcd2009-08-13 15:13:03 -07001169 // Don't run backup, even if requested, if the target app does not have
1170 // the requisite permission
1171 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1172 request.appInfo.packageName) != PackageManager.PERMISSION_GRANTED) {
1173 Log.w(TAG, "Skipping backup of unprivileged package "
1174 + request.appInfo.packageName);
1175 continue;
1176 }
1177
Christopher Tate043dadc2009-06-02 16:11:00 -07001178 IBackupAgent agent = null;
1179 int mode = (request.fullBackup)
1180 ? IApplicationThread.BACKUP_MODE_FULL
1181 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1182 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001183 agent = bindToAgentSynchronous(request.appInfo, mode);
1184 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001185 int result = processOneBackup(request, agent, transport);
1186 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001187 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001188 } catch (SecurityException ex) {
1189 // Try for the next one.
Christopher Tatec7b31e32009-06-10 15:49:30 -07001190 Log.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001191 } finally {
1192 try { // unbind even on timeout, just in case
1193 mActivityManager.unbindBackupAgent(request.appInfo);
1194 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001195 }
1196 }
Dan Egnor01445162009-09-21 17:04:05 -07001197
1198 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001199 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001200
Dan Egnor01445162009-09-21 17:04:05 -07001201 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1202 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001203 final String packageName = request.appInfo.packageName;
Dan Egnor01445162009-09-21 17:04:05 -07001204 if (DEBUG) Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001205
Dan Egnorbb9001c2009-07-27 12:20:13 -07001206 File savedStateName = new File(mStateDir, packageName);
1207 File backupDataName = new File(mDataDir, packageName + ".data");
1208 File newStateName = new File(mStateDir, packageName + ".new");
1209
1210 ParcelFileDescriptor savedState = null;
1211 ParcelFileDescriptor backupData = null;
1212 ParcelFileDescriptor newState = null;
1213
1214 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001215 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001216 try {
1217 // Look up the package info & signatures. This is first so that if it
1218 // throws an exception, there's no file setup yet that would need to
1219 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001220 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1221 // The metadata 'package' is synthetic
1222 packInfo = new PackageInfo();
1223 packInfo.packageName = packageName;
1224 } else {
1225 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001226 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001227 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001228
Christopher Tatec7b31e32009-06-10 15:49:30 -07001229 // In a full backup, we pass a null ParcelFileDescriptor as
1230 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001231 if (!request.fullBackup) {
1232 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001233 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001234 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1235 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001236
Dan Egnorbb9001c2009-07-27 12:20:13 -07001237 backupData = ParcelFileDescriptor.open(backupDataName,
1238 ParcelFileDescriptor.MODE_READ_WRITE |
1239 ParcelFileDescriptor.MODE_CREATE |
1240 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001241
Dan Egnorbb9001c2009-07-27 12:20:13 -07001242 newState = ParcelFileDescriptor.open(newStateName,
1243 ParcelFileDescriptor.MODE_READ_WRITE |
1244 ParcelFileDescriptor.MODE_CREATE |
1245 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001246
Christopher Tate44a27902010-01-27 17:15:49 -08001247 // Initiate the target's backup pass
1248 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1249 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1250 boolean success = waitUntilOperationComplete(token);
1251
1252 if (!success) {
1253 // timeout -- bail out into the failed-transaction logic
1254 throw new RuntimeException("Backup timeout");
1255 }
1256
Dan Egnorbb9001c2009-07-27 12:20:13 -07001257 logBackupComplete(packageName);
1258 if (DEBUG) Log.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001259 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -07001260 Log.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001261 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001262 backupDataName.delete();
1263 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001264 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001265 } finally {
1266 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1267 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1268 try { if (newState != null) newState.close(); } catch (IOException e) {}
1269 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001270 synchronized (mCurrentOpLock) {
1271 mCurrentOperations.clear();
1272 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001273 }
1274
1275 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001276 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001277 try {
1278 int size = (int) backupDataName.length();
1279 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001280 if (result == BackupConstants.TRANSPORT_OK) {
1281 backupData = ParcelFileDescriptor.open(backupDataName,
1282 ParcelFileDescriptor.MODE_READ_ONLY);
1283 result = transport.performBackup(packInfo, backupData);
1284 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001285
Dan Egnor83861e72009-09-17 16:17:55 -07001286 // TODO - We call finishBackup() for each application backed up, because
1287 // we need to know now whether it succeeded or failed. Instead, we should
1288 // hold off on finishBackup() until the end, which implies holding off on
1289 // renaming *all* the output state files (see below) until that happens.
1290
Dan Egnor01445162009-09-21 17:04:05 -07001291 if (result == BackupConstants.TRANSPORT_OK) {
1292 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001293 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001294 } else {
1295 if (DEBUG) Log.i(TAG, "no backup data written; not calling transport");
1296 }
1297
1298 // After successful transport, delete the now-stale data
1299 // and juggle the files so that next time we supply the agent
1300 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001301 if (result == BackupConstants.TRANSPORT_OK) {
1302 backupDataName.delete();
1303 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001304 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001305 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001306 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001307 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001308 } catch (Exception e) {
1309 Log.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001310 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001311 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001312 } finally {
1313 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001314 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001315
Dan Egnor01445162009-09-21 17:04:05 -07001316 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001317 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001318 }
1319
Christopher Tatedf01dea2009-06-09 20:45:02 -07001320
1321 // ----- Restore handling -----
1322
Christopher Tate78dd4a72009-11-04 11:49:08 -08001323 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1324 // If the target resides on the system partition, we allow it to restore
1325 // data from the like-named package in a restore set even if the signatures
1326 // do not match. (Unlike general applications, those flashed to the system
1327 // partition will be signed with the device's platform certificate, so on
1328 // different phones the same system app will have different signatures.)
1329 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1330 if (DEBUG) Log.v(TAG, "System app " + target.packageName + " - skipping sig check");
1331 return true;
1332 }
1333
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001334 // Allow unsigned apps, but not signed on one device and unsigned on the other
1335 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001336 Signature[] deviceSigs = target.signatures;
Christopher Tate6aa41f42009-06-19 14:14:22 -07001337 if (DEBUG) Log.v(TAG, "signaturesMatch(): stored=" + storedSigs
1338 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001339 if ((storedSigs == null || storedSigs.length == 0)
1340 && (deviceSigs == null || deviceSigs.length == 0)) {
1341 return true;
1342 }
1343 if (storedSigs == null || deviceSigs == null) {
1344 return false;
1345 }
1346
Christopher Tateabce4e82009-06-18 18:35:32 -07001347 // !!! TODO: this demands that every stored signature match one
1348 // that is present on device, and does not demand the converse.
1349 // Is this this right policy?
1350 int nStored = storedSigs.length;
1351 int nDevice = deviceSigs.length;
1352
1353 for (int i=0; i < nStored; i++) {
1354 boolean match = false;
1355 for (int j=0; j < nDevice; j++) {
1356 if (storedSigs[i].equals(deviceSigs[j])) {
1357 match = true;
1358 break;
1359 }
1360 }
1361 if (!match) {
1362 return false;
1363 }
1364 }
1365 return true;
1366 }
1367
Christopher Tate44a27902010-01-27 17:15:49 -08001368 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001369 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001370 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001371 private long mToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001372 private File mStateDir;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001373
Christopher Tate5cbbf562009-06-22 16:44:51 -07001374 class RestoreRequest {
1375 public PackageInfo app;
1376 public int storedAppVersion;
1377
1378 RestoreRequest(PackageInfo _app, int _version) {
1379 app = _app;
1380 storedAppVersion = _version;
1381 }
1382 }
1383
Christopher Tate44a27902010-01-27 17:15:49 -08001384 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Dan Egnor156411d2009-06-26 13:20:02 -07001385 long restoreSetToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001386 mTransport = transport;
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001387 Log.d(TAG, "PerformRestoreThread mObserver=" + mObserver);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001388 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001389 mToken = restoreSetToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001390
1391 try {
1392 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1393 } catch (RemoteException e) {
1394 // can't happen; the transport is local
1395 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001396 }
1397
Christopher Tatedf01dea2009-06-09 20:45:02 -07001398 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001399 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001400 if (DEBUG) Log.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tatef2c321a2009-08-10 15:43:36 -07001401 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken));
Christopher Tatedf01dea2009-06-09 20:45:02 -07001402 /**
1403 * Restore sequence:
1404 *
Dan Egnorefe52642009-06-24 00:16:33 -07001405 * 1. get the restore set description for our identity
1406 * 2. for each app in the restore set:
Dan Egnorbb9001c2009-07-27 12:20:13 -07001407 * 2.a. if it's restorable on this device, add it to the restore queue
Dan Egnorefe52642009-06-24 00:16:33 -07001408 * 3. for each app in the restore queue:
1409 * 3.a. clear the app data
1410 * 3.b. get the restore data for the app from the transport
1411 * 3.c. launch the backup agent for the app
1412 * 3.d. agent.doRestore() with the data from the server
1413 * 3.e. unbind the agent [and kill the app?]
1414 * 4. shut down the transport
Dan Egnorbb9001c2009-07-27 12:20:13 -07001415 *
1416 * On errors, we try our best to recover and move on to the next
1417 * application, but if necessary we abort the whole operation --
1418 * the user is waiting, after al.
Christopher Tatedf01dea2009-06-09 20:45:02 -07001419 */
1420
Christopher Tate7d562ec2009-06-25 18:03:43 -07001421 int error = -1; // assume error
1422
Dan Egnorefe52642009-06-24 00:16:33 -07001423 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001424 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001425 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001426 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001427
Dan Egnorefe52642009-06-24 00:16:33 -07001428 // Get the list of all packages which have backup enabled.
1429 // (Include the Package Manager metadata pseudo-package first.)
1430 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1431 PackageInfo omPackage = new PackageInfo();
1432 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1433 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001434
Dan Egnorefe52642009-06-24 00:16:33 -07001435 List<PackageInfo> agentPackages = allAgentPackages();
1436 restorePackages.addAll(agentPackages);
1437
Christopher Tate7d562ec2009-06-25 18:03:43 -07001438 // let the observer know that we're running
1439 if (mObserver != null) {
1440 try {
1441 // !!! TODO: get an actual count from the transport after
1442 // its startRestore() runs?
1443 mObserver.restoreStarting(restorePackages.size());
1444 } catch (RemoteException e) {
1445 Log.d(TAG, "Restore observer died at restoreStarting");
1446 mObserver = null;
1447 }
1448 }
1449
Dan Egnor01445162009-09-21 17:04:05 -07001450 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1451 BackupConstants.TRANSPORT_OK) {
Dan Egnorefe52642009-06-24 00:16:33 -07001452 Log.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001453 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001454 return;
1455 }
1456
1457 String packageName = mTransport.nextRestorePackage();
1458 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001459 Log.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001460 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001461 return;
1462 } else if (packageName.equals("")) {
1463 Log.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001464 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001465 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001466 return;
1467 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1468 Log.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
1469 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001470 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001471 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001472 return;
1473 }
1474
1475 // Pull the Package Manager metadata from the restore set first
1476 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1477 mPackageManager, agentPackages);
1478 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1479
Christopher Tate8c032472009-07-02 14:28:47 -07001480 // Verify that the backup set includes metadata. If not, we can't do
1481 // signature/version verification etc, so we simply do not proceed with
1482 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001483 if (!pmAgent.hasMetadata()) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001484 Log.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001485 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001486 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001487 return;
1488 }
1489
Christopher Tate7d562ec2009-06-25 18:03:43 -07001490 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001491 for (;;) {
1492 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001493
Dan Egnorefe52642009-06-24 00:16:33 -07001494 if (packageName == null) {
Dan Egnorefe52642009-06-24 00:16:33 -07001495 Log.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001496 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001497 return;
1498 } else if (packageName.equals("")) {
1499 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001500 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001501
Christopher Tate7d562ec2009-06-25 18:03:43 -07001502 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001503 try {
1504 mObserver.onUpdate(count);
1505 } catch (RemoteException e) {
1506 Log.d(TAG, "Restore observer died in onUpdate");
1507 mObserver = null;
1508 }
1509 }
1510
Dan Egnorefe52642009-06-24 00:16:33 -07001511 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1512 if (metaInfo == null) {
1513 Log.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001514 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001515 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001516 continue;
1517 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001518
Dan Egnorbb9001c2009-07-27 12:20:13 -07001519 PackageInfo packageInfo;
1520 try {
1521 int flags = PackageManager.GET_SIGNATURES;
1522 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1523 } catch (NameNotFoundException e) {
1524 Log.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001525 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001526 "Package missing on device");
1527 continue;
1528 }
1529
Dan Egnorefe52642009-06-24 00:16:33 -07001530 if (metaInfo.versionCode > packageInfo.versionCode) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001531 String message = "Version " + metaInfo.versionCode
1532 + " > installed version " + packageInfo.versionCode;
1533 Log.w(TAG, "Package " + packageName + ": " + message);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001534 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, message);
Dan Egnorefe52642009-06-24 00:16:33 -07001535 continue;
1536 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001537
Christopher Tate78dd4a72009-11-04 11:49:08 -08001538 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Dan Egnorefe52642009-06-24 00:16:33 -07001539 Log.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001540 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001541 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001542 continue;
1543 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001544
Dan Egnorefe52642009-06-24 00:16:33 -07001545 if (DEBUG) Log.v(TAG, "Package " + packageName
1546 + " restore version [" + metaInfo.versionCode
1547 + "] is compatible with installed version ["
1548 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001549
Christopher Tate5e1ab332009-09-01 20:32:49 -07001550 // Now perform the actual restore: first clear the app's data
1551 // if appropriate
Dan Egnorefe52642009-06-24 00:16:33 -07001552 clearApplicationDataSynchronous(packageName);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001553
1554 // Then set up and bind the agent (with a restricted Application object
1555 // unless the application says otherwise)
1556 boolean useRealApp = (packageInfo.applicationInfo.flags
1557 & ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION) != 0;
1558 if (DEBUG && useRealApp) {
1559 Log.v(TAG, "agent requires real Application subclass for restore");
1560 }
Dan Egnorefe52642009-06-24 00:16:33 -07001561 IBackupAgent agent = bindToAgentSynchronous(
1562 packageInfo.applicationInfo,
Christopher Tate5e1ab332009-09-01 20:32:49 -07001563 (useRealApp ? IApplicationThread.BACKUP_MODE_INCREMENTAL
1564 : IApplicationThread.BACKUP_MODE_RESTORE));
Dan Egnorefe52642009-06-24 00:16:33 -07001565 if (agent == null) {
1566 Log.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001567 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001568 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001569 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001570 }
1571
Christopher Tate5e1ab332009-09-01 20:32:49 -07001572 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001573 try {
1574 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001575 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001576 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001577 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001578 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001579
1580 // The agent was probably running with a stub Application object,
1581 // which isn't a valid run mode for the main app logic. Shut
1582 // down the app so that next time it's launched, it gets the
1583 // usual full initialization.
1584 if ((packageInfo.applicationInfo.flags
1585 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
1586 if (DEBUG) Log.d(TAG, "Restore complete, killing host process of "
1587 + packageInfo.applicationInfo.processName);
1588 mActivityManager.killApplicationProcess(
1589 packageInfo.applicationInfo.processName,
1590 packageInfo.applicationInfo.uid);
1591 }
Dan Egnorefe52642009-06-24 00:16:33 -07001592 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001593 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001594
1595 // if we get this far, report success to the observer
1596 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001597 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001598 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001599 } catch (Exception e) {
1600 Log.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001601 } finally {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001602 if (DEBUG) Log.d(TAG, "finishing restore mObserver=" + mObserver);
1603
Dan Egnorefe52642009-06-24 00:16:33 -07001604 try {
1605 mTransport.finishRestore();
1606 } catch (RemoteException e) {
1607 Log.e(TAG, "Error finishing restore", e);
1608 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001609
1610 if (mObserver != null) {
1611 try {
1612 mObserver.restoreFinished(error);
1613 } catch (RemoteException e) {
1614 Log.d(TAG, "Restore observer died at restoreFinished");
1615 }
1616 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001617
1618 // done; we can finally release the wakelock
1619 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001620 }
1621 }
1622
Dan Egnorefe52642009-06-24 00:16:33 -07001623 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1624 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001625 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001626 final String packageName = app.packageName;
1627
Dan Egnorbb9001c2009-07-27 12:20:13 -07001628 if (DEBUG) Log.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001629
Christopher Tate0749dcd2009-08-13 15:13:03 -07001630 // Don't restore to unprivileged packages
1631 if (mPackageManager.checkPermission(android.Manifest.permission.BACKUP_DATA,
1632 packageName) != PackageManager.PERMISSION_GRANTED) {
1633 Log.d(TAG, "Skipping restore of unprivileged package " + packageName);
1634 }
1635
Christopher Tatec7b31e32009-06-10 15:49:30 -07001636 // !!! TODO: get the dirs from the transport
1637 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001638 File newStateName = new File(mStateDir, packageName + ".new");
1639 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001640
Dan Egnorbb9001c2009-07-27 12:20:13 -07001641 ParcelFileDescriptor backupData = null;
1642 ParcelFileDescriptor newState = null;
1643
Christopher Tate44a27902010-01-27 17:15:49 -08001644 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001645 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001646 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001647 backupData = ParcelFileDescriptor.open(backupDataName,
1648 ParcelFileDescriptor.MODE_READ_WRITE |
1649 ParcelFileDescriptor.MODE_CREATE |
1650 ParcelFileDescriptor.MODE_TRUNCATE);
1651
Dan Egnor01445162009-09-21 17:04:05 -07001652 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001653 Log.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001654 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001655 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001656 }
1657
1658 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001659 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001660 backupData = ParcelFileDescriptor.open(backupDataName,
1661 ParcelFileDescriptor.MODE_READ_ONLY);
1662
Dan Egnorbb9001c2009-07-27 12:20:13 -07001663 newState = ParcelFileDescriptor.open(newStateName,
1664 ParcelFileDescriptor.MODE_READ_WRITE |
1665 ParcelFileDescriptor.MODE_CREATE |
1666 ParcelFileDescriptor.MODE_TRUNCATE);
1667
Christopher Tate44a27902010-01-27 17:15:49 -08001668 // Kick off the restore, checking for hung agents
1669 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1670 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1671 boolean success = waitUntilOperationComplete(token);
1672
1673 if (!success) {
1674 throw new RuntimeException("restore timeout");
1675 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001676
1677 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001678 //
1679 // !!! TODO: the restored data should be migrated on the server
1680 // side into the current dataset. In that case the new state file
1681 // we just created would reflect the data already extant in the
1682 // backend, so there'd be nothing more to do. Until that happens,
1683 // however, we need to make sure that we record the data to the
1684 // current backend dataset. (Yes, this means shipping the data over
1685 // the wire in both directions. That's bad, but consistency comes
1686 // first, then efficiency.) Once we introduce server-side data
1687 // migration to the newly-restored device's dataset, we will change
1688 // the following from a discard of the newly-written state to the
1689 // "correct" operation of renaming into the canonical state blob.
1690 newStateName.delete(); // TODO: remove; see above comment
1691 //newStateName.renameTo(savedStateName); // TODO: replace with this
1692
Dan Egnorbb9001c2009-07-27 12:20:13 -07001693 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001694 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001695 } catch (Exception e) {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001696 Log.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001697 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001698
Christopher Tate96733042009-07-20 14:49:13 -07001699 // If the agent fails restore, it might have put the app's data
1700 // into an incoherent state. For consistency we wipe its data
1701 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001702 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001703 } finally {
1704 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001705 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1706 try { if (newState != null) newState.close(); } catch (IOException e) {}
1707 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001708 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001709 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001710 }
1711 }
1712
Christopher Tate44a27902010-01-27 17:15:49 -08001713 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001714 IBackupTransport mTransport;
1715 PackageInfo mPackage;
1716
Christopher Tate44a27902010-01-27 17:15:49 -08001717 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001718 mTransport = transport;
1719 mPackage = packageInfo;
1720 }
1721
Christopher Tateee0e78a2009-07-02 11:17:03 -07001722 public void run() {
1723 try {
1724 // Clear the on-device backup state to ensure a full backup next time
1725 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1726 File stateFile = new File(stateDir, mPackage.packageName);
1727 stateFile.delete();
1728
1729 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001730 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001731 mTransport.clearBackupData(mPackage);
1732 } catch (RemoteException e) {
1733 // can't happen; the transport is local
1734 } finally {
1735 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001736 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001737 mTransport.finishBackup();
1738 } catch (RemoteException e) {
1739 // can't happen; the transport is local
1740 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001741
1742 // Last but not least, release the cpu
1743 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001744 }
1745 }
1746 }
1747
Christopher Tate44a27902010-01-27 17:15:49 -08001748 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001749 HashSet<String> mQueue;
1750
Christopher Tate44a27902010-01-27 17:15:49 -08001751 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001752 mQueue = transportNames;
1753 }
1754
Christopher Tate4cc86e12009-09-21 19:36:51 -07001755 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001756 try {
1757 for (String transportName : mQueue) {
1758 IBackupTransport transport = getTransport(transportName);
1759 if (transport == null) {
1760 Log.e(TAG, "Requested init for " + transportName + " but not found");
1761 continue;
1762 }
1763
Dan Egnor726247c2009-09-29 19:12:31 -07001764 Log.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001765 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001766 long startRealtime = SystemClock.elapsedRealtime();
1767 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001768
Christopher Tate4cc86e12009-09-21 19:36:51 -07001769 if (status == BackupConstants.TRANSPORT_OK) {
1770 status = transport.finishBackup();
1771 }
1772
1773 // Okay, the wipe really happened. Clean up our local bookkeeping.
1774 if (status == BackupConstants.TRANSPORT_OK) {
Dan Egnor726247c2009-09-29 19:12:31 -07001775 Log.i(TAG, "Device init successful");
1776 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001777 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001778 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001779 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001780 synchronized (mQueueLock) {
1781 recordInitPendingLocked(false, transportName);
1782 }
Dan Egnor726247c2009-09-29 19:12:31 -07001783 } else {
1784 // If this didn't work, requeue this one and try again
1785 // after a suitable interval
1786 Log.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001787 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001788 synchronized (mQueueLock) {
1789 recordInitPendingLocked(true, transportName);
1790 }
1791 // do this via another alarm to make sure of the wakelock states
1792 long delay = transport.requestBackupTime();
1793 if (DEBUG) Log.w(TAG, "init failed on "
1794 + transportName + " resched in " + delay);
1795 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1796 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001797 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001798 }
1799 } catch (RemoteException e) {
1800 // can't happen; the transports are local
1801 } catch (Exception e) {
1802 Log.e(TAG, "Unexpected error performing init", e);
1803 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001804 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001805 mWakelock.release();
1806 }
1807 }
1808 }
1809
Christopher Tatedf01dea2009-06-09 20:45:02 -07001810
Christopher Tate487529a2009-04-29 14:03:25 -07001811 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001812
Dan Egnor852f8e42009-09-30 11:20:45 -07001813 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001814 // Record that we need a backup pass for the caller. Since multiple callers
1815 // may share a uid, we need to note all candidates within that uid and schedule
1816 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001817 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001818
Christopher Tate63d27002009-06-16 17:16:42 -07001819 // If the caller does not hold the BACKUP permission, it can only request a
1820 // backup of its own data.
1821 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001822 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001823 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1824 targets = mBackupParticipants.get(Binder.getCallingUid());
1825 } else {
1826 // a caller with full permission can ask to back up any participating app
1827 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07001828 targets = new HashSet<ApplicationInfo>();
1829 int N = mBackupParticipants.size();
1830 for (int i = 0; i < N; i++) {
1831 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1832 if (s != null) {
1833 targets.addAll(s);
1834 }
1835 }
1836 }
Christopher Tate487529a2009-04-29 14:03:25 -07001837 if (targets != null) {
1838 synchronized (mQueueLock) {
1839 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07001840 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07001841 // validate the caller-supplied package name against the known set of
1842 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07001843 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04001844 // Add the caller to the set of pending backups. If there is
1845 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07001846 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07001847 if (mPendingBackups.put(app, req) == null) {
1848 // Journal this request in case of crash. The put()
1849 // operation returned null when this package was not already
1850 // in the set; we want to avoid touching the disk redundantly.
1851 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07001852
Christopher Tate22b60d82009-07-07 16:36:02 -07001853 if (DEBUG) {
1854 int numKeys = mPendingBackups.size();
1855 Log.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
1856 for (BackupRequest b : mPendingBackups.values()) {
1857 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
1858 }
1859 }
1860 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001861 }
1862 }
Christopher Tate487529a2009-04-29 14:03:25 -07001863 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001864 } else {
Christopher Tate73e02522009-07-15 14:18:26 -07001865 Log.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
1866 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07001867 }
1868 }
Christopher Tate46758122009-05-06 11:22:00 -07001869
Christopher Tatecde87f42009-06-12 12:55:53 -07001870 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001871 RandomAccessFile out = null;
1872 try {
1873 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
1874 out = new RandomAccessFile(mJournal, "rws");
1875 out.seek(out.length());
1876 out.writeUTF(str);
1877 } catch (IOException e) {
1878 Log.e(TAG, "Can't write " + str + " to backup journal", e);
1879 mJournal = null;
1880 } finally {
1881 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07001882 }
1883 }
1884
Christopher Tateee0e78a2009-07-02 11:17:03 -07001885 // Clear the given package's backup data from the current transport
1886 public void clearBackupData(String packageName) {
1887 if (DEBUG) Log.v(TAG, "clearBackupData() of " + packageName);
1888 PackageInfo info;
1889 try {
1890 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
1891 } catch (NameNotFoundException e) {
1892 Log.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
1893 return;
1894 }
1895
1896 // If the caller does not hold the BACKUP permission, it can only request a
1897 // wipe of its own backed-up data.
1898 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07001899 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07001900 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1901 apps = mBackupParticipants.get(Binder.getCallingUid());
1902 } else {
1903 // a caller with full permission can ask to back up any participating app
1904 // !!! TODO: allow data-clear of ANY app?
1905 if (DEBUG) Log.v(TAG, "Privileged caller, allowing clear of other apps");
1906 apps = new HashSet<ApplicationInfo>();
1907 int N = mBackupParticipants.size();
1908 for (int i = 0; i < N; i++) {
1909 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
1910 if (s != null) {
1911 apps.addAll(s);
1912 }
1913 }
1914 }
1915
1916 // now find the given package in the set of candidate apps
1917 for (ApplicationInfo app : apps) {
1918 if (app.packageName.equals(packageName)) {
1919 if (DEBUG) Log.v(TAG, "Found the app - running clear process");
1920 // found it; fire off the clear request
1921 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07001922 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07001923 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001924 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
1925 new ClearParams(getTransport(mCurrentTransport), info));
1926 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07001927 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07001928 }
1929 break;
1930 }
1931 }
1932 }
1933
Christopher Tateace7f092009-06-15 18:07:25 -07001934 // Run a backup pass immediately for any applications that have declared
1935 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07001936 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04001937 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07001938
Christopher Tateace7f092009-06-15 18:07:25 -07001939 if (DEBUG) Log.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07001940 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07001941 // Because the alarms we are using can jitter, and we want an *immediate*
1942 // backup pass to happen, we restart the timer beginning with "next time,"
1943 // then manually fire the backup trigger intent ourselves.
1944 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07001945 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07001946 mRunBackupIntent.send();
1947 } catch (PendingIntent.CanceledException e) {
1948 // should never happen
1949 Log.e(TAG, "run-backup intent cancelled!");
1950 }
Christopher Tate46758122009-05-06 11:22:00 -07001951 }
1952 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001953
Christopher Tate8031a3d2009-07-06 16:36:05 -07001954 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07001955 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001956 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
1957 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07001958
Christopher Tate4cc86e12009-09-21 19:36:51 -07001959 Log.i(TAG, "Backup enabled => " + enable);
1960
Christopher Tate6ef58a12009-06-29 14:56:28 -07001961 boolean wasEnabled = mEnabled;
1962 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07001963 Settings.Secure.putInt(mContext.getContentResolver(),
1964 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07001965 mEnabled = enable;
1966 }
1967
Christopher Tate49401dd2009-07-01 12:34:29 -07001968 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07001969 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07001970 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07001971 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07001972 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07001973 // No longer enabled, so stop running backups
Christopher Tate4cc86e12009-09-21 19:36:51 -07001974 if (DEBUG) Log.i(TAG, "Opting out of backup");
1975
Christopher Tateb6787f22009-07-02 17:40:45 -07001976 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001977
1978 // This also constitutes an opt-out, so we wipe any data for
1979 // this device from the backend. We start that process with
1980 // an alarm in order to guarantee wakelock states.
1981 if (wasEnabled && mProvisioned) {
1982 // NOTE: we currently flush every registered transport, not just
1983 // the currently-active one.
1984 HashSet<String> allTransports;
1985 synchronized (mTransports) {
1986 allTransports = new HashSet<String>(mTransports.keySet());
1987 }
1988 // build the set of transports for which we are posting an init
1989 for (String transport : allTransports) {
1990 recordInitPendingLocked(true, transport);
1991 }
1992 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1993 mRunInitIntent);
1994 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001995 }
1996 }
Christopher Tate49401dd2009-07-01 12:34:29 -07001997 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07001998
Christopher Tate8031a3d2009-07-06 16:36:05 -07001999 // Mark the backup service as having been provisioned
2000 public void setBackupProvisioned(boolean available) {
2001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2002 "setBackupProvisioned");
2003
2004 boolean wasProvisioned = mProvisioned;
2005 synchronized (this) {
2006 Settings.Secure.putInt(mContext.getContentResolver(),
2007 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2008 mProvisioned = available;
2009 }
2010
2011 synchronized (mQueueLock) {
2012 if (available && !wasProvisioned && mEnabled) {
2013 // we're now good to go, so start the backup alarms
2014 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2015 } else if (!available) {
2016 // No longer enabled, so stop running backups
2017 Log.w(TAG, "Backup service no longer provisioned");
2018 mAlarmManager.cancel(mRunBackupIntent);
2019 }
2020 }
2021 }
2022
2023 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002024 // We used to use setInexactRepeating(), but that may be linked to
2025 // backups running at :00 more often than not, creating load spikes.
2026 // Schedule at an exact time for now, and also add a bit of "fuzz".
2027
2028 Random random = new Random();
2029 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2030 random.nextInt(FUZZ_MILLIS);
2031 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2032 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002033 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002034 }
2035
Christopher Tate6ef58a12009-06-29 14:56:28 -07002036 // Report whether the backup mechanism is currently enabled
2037 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002038 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002039 return mEnabled; // no need to synchronize just to read it
2040 }
2041
Christopher Tate91717492009-06-26 21:07:13 -07002042 // Report the name of the currently active transport
2043 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002044 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002045 "getCurrentTransport");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002046 Log.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002047 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002048 }
2049
Christopher Tate91717492009-06-26 21:07:13 -07002050 // Report all known, available backup transports
2051 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002052 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002053
Christopher Tate91717492009-06-26 21:07:13 -07002054 String[] list = null;
2055 ArrayList<String> known = new ArrayList<String>();
2056 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2057 if (entry.getValue() != null) {
2058 known.add(entry.getKey());
2059 }
2060 }
2061
2062 if (known.size() > 0) {
2063 list = new String[known.size()];
2064 known.toArray(list);
2065 }
2066 return list;
2067 }
2068
2069 // Select which transport to use for the next backup operation. If the given
2070 // name is not one of the available transports, no action is taken and the method
2071 // returns null.
2072 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002073 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002074
2075 synchronized (mTransports) {
2076 String prevTransport = null;
2077 if (mTransports.get(transport) != null) {
2078 prevTransport = mCurrentTransport;
2079 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002080 Settings.Secure.putString(mContext.getContentResolver(),
2081 Settings.Secure.BACKUP_TRANSPORT, transport);
Christopher Tate91717492009-06-26 21:07:13 -07002082 Log.v(TAG, "selectBackupTransport() set " + mCurrentTransport
2083 + " returning " + prevTransport);
2084 } else {
2085 Log.w(TAG, "Attempt to select unavailable transport " + transport);
2086 }
2087 return prevTransport;
2088 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002089 }
2090
2091 // Callback: a requested backup agent has been instantiated. This should only
2092 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002093 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002094 synchronized(mAgentConnectLock) {
2095 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2096 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
2097 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2098 mConnectedAgent = agent;
2099 mConnecting = false;
2100 } else {
2101 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2102 + " claiming agent connected");
2103 }
2104 mAgentConnectLock.notifyAll();
2105 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002106 }
2107
2108 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2109 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002110 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002111 public void agentDisconnected(String packageName) {
2112 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002113 synchronized(mAgentConnectLock) {
2114 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2115 mConnectedAgent = null;
2116 mConnecting = false;
2117 } else {
2118 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
2119 + " claiming agent disconnected");
2120 }
2121 mAgentConnectLock.notifyAll();
2122 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002123 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002124
Christopher Tate8c850b72009-06-07 19:33:20 -07002125 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002126 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002128
2129 synchronized(this) {
2130 if (mActiveRestoreSession != null) {
2131 Log.d(TAG, "Restore session requested but one already active");
2132 return null;
2133 }
Christopher Tate80202c82010-01-25 19:37:47 -08002134 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002135 }
2136 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002137 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002138
Christopher Tate44a27902010-01-27 17:15:49 -08002139 // Note that a currently-active backup agent has notified us that it has
2140 // completed the given outstanding asynchronous backup/restore operation.
2141 public void opComplete(int token) {
2142 synchronized (mCurrentOpLock) {
2143 if (DEBUG) Log.v(TAG, "opComplete: " + token);
2144 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2145 mCurrentOpLock.notifyAll();
2146 }
2147 }
2148
Christopher Tate9b3905c2009-06-08 15:24:01 -07002149 // ----- Restore session -----
2150
Christopher Tate80202c82010-01-25 19:37:47 -08002151 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002152 private static final String TAG = "RestoreSession";
2153
Christopher Tate9b3905c2009-06-08 15:24:01 -07002154 private IBackupTransport mRestoreTransport = null;
2155 RestoreSet[] mRestoreSets = null;
2156
Christopher Tate80202c82010-01-25 19:37:47 -08002157 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002158 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002159 }
2160
2161 // --- Binder interface ---
Dan Egnor0084da52009-07-29 12:57:16 -07002162 public synchronized RestoreSet[] getAvailableRestoreSets() {
Joe Onorato5933a492009-07-23 18:24:08 -04002163 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002164 "getAvailableRestoreSets");
2165
Christopher Tatef68eb502009-06-16 11:02:01 -07002166 try {
Christopher Tate43383042009-07-13 15:17:13 -07002167 if (mRestoreTransport == null) {
2168 Log.w(TAG, "Null transport getting restore sets");
Dan Egnor0084da52009-07-29 12:57:16 -07002169 return null;
2170 }
2171 if (mRestoreSets == null) { // valid transport; do the one-time fetch
Christopher Tate9b3905c2009-06-08 15:24:01 -07002172 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002173 if (mRestoreSets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002174 }
2175 return mRestoreSets;
Dan Egnor0084da52009-07-29 12:57:16 -07002176 } catch (Exception e) {
2177 Log.e(TAG, "Error in getAvailableRestoreSets", e);
2178 return null;
Christopher Tatef68eb502009-06-16 11:02:01 -07002179 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002180 }
2181
Dan Egnor0084da52009-07-29 12:57:16 -07002182 public synchronized int performRestore(long token, IRestoreObserver observer) {
2183 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2184 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002185
Christopher Tatef2c321a2009-08-10 15:43:36 -07002186 if (DEBUG) Log.d(TAG, "performRestore token=" + Long.toHexString(token)
2187 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002188
Dan Egnor0084da52009-07-29 12:57:16 -07002189 if (mRestoreTransport == null || mRestoreSets == null) {
2190 Log.e(TAG, "Ignoring performRestore() with no restore set");
2191 return -1;
2192 }
2193
Christopher Tate21ab6a52009-09-24 18:01:46 -07002194 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002195 for (int i = 0; i < mRestoreSets.length; i++) {
2196 if (token == mRestoreSets[i].token) {
2197 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002198 mWakelock.acquire();
2199 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2200 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2201 mBackupHandler.sendMessage(msg);
2202 Binder.restoreCallingIdentity(oldId);
2203 return 0;
2204 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002205 }
2206 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002207
2208 Log.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002209 return -1;
2210 }
2211
Dan Egnor0084da52009-07-29 12:57:16 -07002212 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002213 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002214 "endRestoreSession");
2215
Dan Egnor0084da52009-07-29 12:57:16 -07002216 if (DEBUG) Log.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002217
Dan Egnor0084da52009-07-29 12:57:16 -07002218 synchronized (this) {
2219 try {
2220 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2221 } catch (Exception e) {
2222 Log.e(TAG, "Error in finishRestore", e);
2223 } finally {
2224 mRestoreTransport = null;
2225 }
2226 }
2227
2228 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002229 if (BackupManagerService.this.mActiveRestoreSession == this) {
2230 BackupManagerService.this.mActiveRestoreSession = null;
2231 } else {
2232 Log.e(TAG, "ending non-current restore session");
2233 }
2234 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002235 }
2236 }
2237
Christopher Tate043dadc2009-06-02 16:11:00 -07002238
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002239 @Override
2240 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2241 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002242 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002243 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002244 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tate55f931a2009-09-29 17:17:34 -07002245 pw.println("Last backup pass: " + mLastBackupPass
2246 + " (now = " + System.currentTimeMillis() + ')');
2247 pw.println(" next scheduled: " + mNextBackupPass);
2248
Christopher Tate91717492009-06-26 21:07:13 -07002249 pw.println("Available transports:");
2250 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002251 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2252 try {
2253 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2254 for (File f : dir.listFiles()) {
2255 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2256 }
2257 } catch (RemoteException e) {
2258 Log.e(TAG, "Error in transportDirName()", e);
2259 pw.println(" Error: " + e);
2260 }
Christopher Tate91717492009-06-26 21:07:13 -07002261 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002262
2263 pw.println("Pending init: " + mPendingInits.size());
2264 for (String s : mPendingInits) {
2265 pw.println(" " + s);
2266 }
2267
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002268 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002269 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002270 for (int i=0; i<N; i++) {
2271 int uid = mBackupParticipants.keyAt(i);
2272 pw.print(" uid: ");
2273 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002274 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2275 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002276 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002277 }
2278 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002279
Christopher Tate73e02522009-07-15 14:18:26 -07002280 pw.println("Ever backed up: " + mEverStoredApps.size());
2281 for (String pkg : mEverStoredApps) {
2282 pw.println(" " + pkg);
2283 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002284
2285 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002286 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002287 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002288 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002289 }
2290 }
Christopher Tate487529a2009-04-29 14:03:25 -07002291}